Merge branch 'master' of https://github.com/Microsoft/TypeScript into typedefForJsdoc

# Conflicts:
#	src/compiler/diagnosticMessages.json
#	src/services/services.ts
This commit is contained in:
zhengbli 2016-04-13 16:57:35 -07:00
commit a3d74ad550
764 changed files with 63419 additions and 64736 deletions

2
.gitignore vendored
View File

@ -26,6 +26,8 @@ rwc-report.html
*.swp
build.json
*.actual
tests/webTestServer.js
tests/webTestServer.js.map
tests/webhost/*.d.ts
tests/webhost/webtsc.js
tests/cases/**/*.js

View File

@ -165,18 +165,47 @@ var harnessSources = harnessCoreSources.concat([
return path.join(serverDirectory, f);
}));
var librarySourceMap = [
{ target: "lib.core.d.ts", sources: ["header.d.ts", "core.d.ts"] },
{ target: "lib.dom.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "dom.generated.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["importcore.d.ts", "intl.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scriptHost.d.ts", sources: ["importcore.d.ts", "scriptHost.d.ts"], },
{ target: "lib.d.ts", sources: ["header.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"], },
{ target: "lib.core.es6.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts"]},
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es6.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] },
{ target: "lib.core.es7.d.ts", sources: ["header.d.ts", "core.d.ts", "es6.d.ts", "es7.d.ts"]},
{ target: "lib.es7.d.ts", sources: ["header.d.ts", "es6.d.ts", "es7.d.ts", "core.d.ts", "intl.d.ts", "dom.generated.d.ts", "dom.es6.d.ts", "webworker.importscripts.d.ts", "scriptHost.d.ts"] }
var es2015LibrarySources = [
"es2015.core.d.ts",
"es2015.collection.d.ts",
"es2015.generator.d.ts",
"es2015.iterable.d.ts",
"es2015.promise.d.ts",
"es2015.proxy.d.ts",
"es2015.reflect.d.ts",
"es2015.symbol.d.ts",
"es2015.symbol.wellknown.d.ts",
];
var es2015LibrarySourceMap = es2015LibrarySources.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
});
var es2016LibrarySource = [ "es2016.array.include.d.ts" ];
var es2016LibrarySourceMap = es2016LibrarySource.map(function(source) {
return { target: "lib." + source, sources: ["header.d.ts", source] };
})
var hostsLibrarySources = ["dom.generated.d.ts", "webworker.importscripts.d.ts", "scripthost.d.ts"]
var librarySourceMap = [
// Host library
{ target: "lib.dom.d.ts", sources: ["header.d.ts", "dom.generated.d.ts"], },
{ target: "lib.dom.iterable.d.ts", sources: ["header.d.ts", "dom.iterable.d.ts"], },
{ target: "lib.webworker.d.ts", sources: ["header.d.ts", "webworker.generated.d.ts"], },
{ target: "lib.scripthost.d.ts", sources: ["header.d.ts", "scripthost.d.ts"], },
// JavaScript library
{ target: "lib.es5.d.ts", sources: ["header.d.ts", "es5.d.ts"] },
{ target: "lib.es2015.d.ts", sources: ["header.d.ts", "es2015.d.ts"] },
{ target: "lib.es2016.d.ts", sources: ["header.d.ts", "es2016.d.ts"] },
// JavaScript + all host library
{ target: "lib.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(hostsLibrarySources), },
{ target: "lib.es6.d.ts", sources: ["header.d.ts", "es5.d.ts"].concat(es2015LibrarySources, hostsLibrarySources), },
].concat(es2015LibrarySourceMap, es2016LibrarySourceMap);
var libraryTargets = librarySourceMap.map(function (f) {
return path.join(builtLocalDirectory, f.target);
});
@ -215,7 +244,7 @@ function concatenateFiles(destinationFile, sourceFiles) {
}
var useDebugMode = true;
var host = (process.env.host || process.env.TYPESCRIPT_HOST || "node");
var host = (process.env.TYPESCRIPT_HOST || process.env.host || "node");
var compilerFilename = "tsc.js";
var LKGCompiler = path.join(LKGDirectory, compilerFilename);
var builtLocalCompiler = path.join(builtLocalDirectory, compilerFilename);
@ -874,7 +903,6 @@ task("update-sublime", ["local", serverFile], function() {
var tslintRuleDir = "scripts/tslint";
var tslintRules = ([
"nextLineRule",
"noNullRule",
"preferConstRule",
"booleanTriviaRule",
"typeOperatorSpacingRule",

5255
lib/lib.core.es6.d.ts vendored

File diff suppressed because it is too large Load Diff

5344
lib/lib.core.es7.d.ts vendored

File diff suppressed because it is too large Load Diff

6997
lib/lib.d.ts vendored

File diff suppressed because it is too large Load Diff

7143
lib/lib.dom.d.ts vendored

File diff suppressed because it is too large Load Diff

29
lib/lib.dom.iterable.d.ts vendored Normal file
View File

@ -0,0 +1,29 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.dom.generated.d.ts" />
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}
interface NodeList {
[Symbol.iterator](): IterableIterator<Node>
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>
}

86
lib/lib.es2015.collection.d.ts vendored Normal file
View File

@ -0,0 +1,86 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;

499
lib/lib.es2015.core.d.ts vendored Normal file
View File

@ -0,0 +1,499 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
big(): string;
/** Returns a <blink> HTML element */
blink(): string;
/** Returns a <b> HTML element */
bold(): string;
/** Returns a <tt> HTML element */
fixed(): string
/** Returns a <font> HTML element and sets the color attribute value */
fontcolor(color: string): string
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an <i> HTML element */
italics(): string;
/** Returns an <a> HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a <small> HTML element */
small(): string;
/** Returns a <strike> HTML element */
strike(): string;
/** Returns a <sub> HTML element */
sub(): string;
/** Returns a <sup> HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}

26
lib/lib.es2015.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />

28
lib/lib.es2015.generator.d.ts vendored Normal file
View File

@ -0,0 +1,28 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;

389
lib/lib.es2015.iterable.d.ts vendored Normal file
View File

@ -0,0 +1,389 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface IteratorResult<T> {
done: boolean;
value?: T;
}
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface IterableIterator<T> extends Iterator<T> { }
interface Array<T> {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
interface Map<K, V> {
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
}
interface MapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
}
interface WeakMap<K, V> { }
interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Promise<T> { }
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}

97
lib/lib.es2015.promise.d.ts vendored Normal file
View File

@ -0,0 +1,97 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject(reason: any): Promise<void>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;

38
lib/lib.es2015.proxy.d.ts vendored Normal file
View File

@ -0,0 +1,38 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
deleteProperty? (target: T, p: PropertyKey): boolean;
defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;

32
lib/lib.es2015.reflect.d.ts vendored Normal file
View File

@ -0,0 +1,32 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}

52
lib/lib.es2015.symbol.d.ts vendored Normal file
View File

@ -0,0 +1,52 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string|number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;

372
lib/lib.es2015.symbol.wellknown.d.ts vendored Normal file
View File

@ -0,0 +1,372 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
interface Symbol {
readonly [Symbol.toStringTag]: "Symbol";
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
[Symbol.unscopables](): {
copyWithin: boolean;
entries: boolean;
fill: boolean;
find: boolean;
findIndex: boolean;
keys: boolean;
values: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
interface Promise<T> {
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
readonly [Symbol.species]: Function;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
[Symbol.species](): RegExpConstructor;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
readonly [Symbol.toStringTag]: "DataView";
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}

105
lib/lib.es2016.array.include.d.ts vendored Normal file
View File

@ -0,0 +1,105 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}

18
lib/lib.es2016.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />

View File

@ -231,14 +231,16 @@ interface Function {
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(thisArg: any, argArray?: any): any;
apply<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U;
apply(this: Function, thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(thisArg: any, ...argArray: any[]): any;
call<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): U;
call(this: Function, thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body as the original function.
@ -246,7 +248,8 @@ interface Function {
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;
bind<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): (this: void, ...argArray: any[]) => U;
bind(this: Function, thisArg: any, ...argArray: any[]): any;
prototype: any;
readonly length: number;
@ -320,13 +323,13 @@ interface String {
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
match(regexp: string): RegExpMatchArray;
match(regexp: string): RegExpMatchArray | null;
/**
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param regexp A regular expression object that contains the regular expression pattern and applicable flags.
*/
match(regexp: RegExp): RegExpMatchArray;
match(regexp: RegExp): RegExpMatchArray | null;
/**
* Replaces text in a string, using a regular expression or search string.
@ -829,7 +832,7 @@ interface RegExp {
* Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search.
* @param string The String object or string literal on which to perform the search.
*/
exec(string: string): RegExpExecArray;
exec(string: string): RegExpExecArray | null;
/**
* Returns a Boolean value that indicates whether or not a pattern exists in a searched string.
@ -852,7 +855,7 @@ interface RegExp {
lastIndex: number;
// Non-standard extensions
compile(): RegExp;
compile(): this;
}
interface RegExpConstructor {
@ -1124,7 +1127,7 @@ interface Array<T> {
/**
* Removes the last element from an array and returns it.
*/
pop(): T;
pop(): T | undefined;
/**
* Combines two or more arrays.
* @param items Additional items to add to the end of array1.
@ -1142,7 +1145,7 @@ interface Array<T> {
/**
* Removes the first element from an array and returns it.
*/
shift(): T;
shift(): T | undefined;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
@ -1535,7 +1538,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -1546,7 +1549,7 @@ interface Int8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -1808,7 +1811,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -1819,7 +1822,7 @@ interface Uint8Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2082,7 +2085,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2093,7 +2096,7 @@ interface Uint8ClampedArray {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2355,7 +2358,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2366,7 +2369,7 @@ interface Int16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2629,7 +2632,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2640,7 +2643,7 @@ interface Uint16Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -2902,7 +2905,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -2913,7 +2916,7 @@ interface Int32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3175,7 +3178,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3186,7 +3189,7 @@ interface Uint32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3448,7 +3451,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3459,7 +3462,7 @@ interface Float32Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3722,7 +3725,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number;
find(predicate: (value: number, index: number, obj: Array<number>) => boolean, thisArg?: any): number | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
@ -3733,7 +3736,7 @@ interface Float64Array {
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: number) => boolean, thisArg?: any): number;
findIndex(predicate: (value: number) => boolean, thisArg?: any): number | undefined;
/**
* Performs the specified action for each element in an array.
@ -3920,3 +3923,204 @@ interface Float64ArrayConstructor {
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
declare const Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. 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.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}

9783
lib/lib.es6.d.ts vendored

File diff suppressed because it is too large Load Diff

18829
lib/lib.es7.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,7 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference path="lib.core.d.ts" />
/// <reference no-default-lib="true"/>
/////////////////////////////

733
lib/lib.webworker.d.ts vendored

File diff suppressed because it is too large Load Diff

8054
lib/tsc.js

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

390
lib/typescript.d.ts vendored
View File

@ -167,163 +167,166 @@ declare namespace ts {
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
FromKeyword = 134,
GlobalKeyword = 135,
OfKeyword = 136,
QualifiedName = 137,
ComputedPropertyName = 138,
TypeParameter = 139,
Parameter = 140,
Decorator = 141,
PropertySignature = 142,
PropertyDeclaration = 143,
MethodSignature = 144,
MethodDeclaration = 145,
Constructor = 146,
GetAccessor = 147,
SetAccessor = 148,
CallSignature = 149,
ConstructSignature = 150,
IndexSignature = 151,
TypePredicate = 152,
TypeReference = 153,
FunctionType = 154,
ConstructorType = 155,
TypeQuery = 156,
TypeLiteral = 157,
ArrayType = 158,
TupleType = 159,
UnionType = 160,
IntersectionType = 161,
ParenthesizedType = 162,
ThisType = 163,
StringLiteralType = 164,
ObjectBindingPattern = 165,
ArrayBindingPattern = 166,
BindingElement = 167,
ArrayLiteralExpression = 168,
ObjectLiteralExpression = 169,
PropertyAccessExpression = 170,
ElementAccessExpression = 171,
CallExpression = 172,
NewExpression = 173,
TaggedTemplateExpression = 174,
TypeAssertionExpression = 175,
ParenthesizedExpression = 176,
FunctionExpression = 177,
ArrowFunction = 178,
DeleteExpression = 179,
TypeOfExpression = 180,
VoidExpression = 181,
AwaitExpression = 182,
PrefixUnaryExpression = 183,
PostfixUnaryExpression = 184,
BinaryExpression = 185,
ConditionalExpression = 186,
TemplateExpression = 187,
YieldExpression = 188,
SpreadElementExpression = 189,
ClassExpression = 190,
OmittedExpression = 191,
ExpressionWithTypeArguments = 192,
AsExpression = 193,
TemplateSpan = 194,
SemicolonClassElement = 195,
Block = 196,
VariableStatement = 197,
EmptyStatement = 198,
ExpressionStatement = 199,
IfStatement = 200,
DoStatement = 201,
WhileStatement = 202,
ForStatement = 203,
ForInStatement = 204,
ForOfStatement = 205,
ContinueStatement = 206,
BreakStatement = 207,
ReturnStatement = 208,
WithStatement = 209,
SwitchStatement = 210,
LabeledStatement = 211,
ThrowStatement = 212,
TryStatement = 213,
DebuggerStatement = 214,
VariableDeclaration = 215,
VariableDeclarationList = 216,
FunctionDeclaration = 217,
ClassDeclaration = 218,
InterfaceDeclaration = 219,
TypeAliasDeclaration = 220,
EnumDeclaration = 221,
ModuleDeclaration = 222,
ModuleBlock = 223,
CaseBlock = 224,
ImportEqualsDeclaration = 225,
ImportDeclaration = 226,
ImportClause = 227,
NamespaceImport = 228,
NamedImports = 229,
ImportSpecifier = 230,
ExportAssignment = 231,
ExportDeclaration = 232,
NamedExports = 233,
ExportSpecifier = 234,
MissingDeclaration = 235,
ExternalModuleReference = 236,
JsxElement = 237,
JsxSelfClosingElement = 238,
JsxOpeningElement = 239,
JsxText = 240,
JsxClosingElement = 241,
JsxAttribute = 242,
JsxSpreadAttribute = 243,
JsxExpression = 244,
CaseClause = 245,
DefaultClause = 246,
HeritageClause = 247,
CatchClause = 248,
PropertyAssignment = 249,
ShorthandPropertyAssignment = 250,
EnumMember = 251,
SourceFile = 252,
JSDocTypeExpression = 253,
JSDocAllType = 254,
JSDocUnknownType = 255,
JSDocArrayType = 256,
JSDocUnionType = 257,
JSDocTupleType = 258,
JSDocNullableType = 259,
JSDocNonNullableType = 260,
JSDocRecordType = 261,
JSDocRecordMember = 262,
JSDocTypeReference = 263,
JSDocOptionalType = 264,
JSDocFunctionType = 265,
JSDocVariadicType = 266,
JSDocConstructorType = 267,
JSDocThisType = 268,
JSDocComment = 269,
JSDocTag = 270,
JSDocParameterTag = 271,
JSDocReturnTag = 272,
JSDocTypeTag = 273,
JSDocTemplateTag = 274,
SyntaxList = 275,
Count = 276,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 136,
LastKeyword = 137,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 152,
LastTypeNode = 164,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 136,
LastToken = 137,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@ -332,7 +335,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 137,
FirstNode = 138,
}
enum NodeFlags {
None = 0,
@ -366,12 +369,13 @@ declare namespace ts {
JavaScriptFile = 134217728,
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
AccessibilityModifier = 28,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
ContextFlags = 62914560,
ContextFlags = 197132288,
TypeExcludesFlags = 41943040,
}
enum JsxFlags {
@ -401,6 +405,9 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@ -702,6 +709,7 @@ declare namespace ts {
dotToken: Node;
name: Identifier;
}
type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
@ -731,6 +739,9 @@ declare namespace ts {
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
@ -854,6 +865,7 @@ declare namespace ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@ -923,6 +935,10 @@ declare namespace ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
@ -1044,6 +1060,7 @@ declare namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
/**
@ -1066,7 +1083,7 @@ declare namespace ts {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
class OperationCanceledException {
}
@ -1141,6 +1158,7 @@ declare namespace ts {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[];
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
@ -1186,7 +1204,7 @@ declare namespace ts {
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@ -1310,6 +1328,7 @@ declare namespace ts {
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
}
interface SymbolTable {
[index: string]: Symbol;
@ -1394,6 +1413,7 @@ declare namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType?: Type;
}
enum IndexKind {
String = 0,
@ -1442,10 +1462,12 @@ declare namespace ts {
type RootPaths = string[];
type PathSubstitutions = Map<string[]>;
type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@ -1455,6 +1477,7 @@ declare namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@ -1464,6 +1487,7 @@ declare namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@ -1492,11 +1516,30 @@ declare namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
interface DiscoverTypingsInfo {
fileNames: string[];
projectRootPath: string;
safeListPath: string;
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
}
enum ModuleKind {
None = 0,
@ -1540,6 +1583,7 @@ declare namespace ts {
}
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
@ -1557,16 +1601,29 @@ declare namespace ts {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
primary: boolean;
resolvedFileName?: string;
}
interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* 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[];
}
interface TextSpan {
start: number;
@ -1578,8 +1635,8 @@ declare namespace ts {
}
}
declare namespace ts {
type FileWatcherCallback = (path: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (path: string) => void;
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface System {
args: string[];
newLine: string;
@ -1587,7 +1644,7 @@ declare namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@ -1596,6 +1653,8 @@ declare namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@ -1603,7 +1662,7 @@ declare namespace ts {
close(): void;
}
interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
var sys: System;
@ -1685,17 +1744,26 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
const version: string;
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
@ -1705,7 +1773,6 @@ declare namespace ts {
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@ -1735,6 +1802,10 @@ declare namespace ts {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
}
declare namespace ts {
/** The version of the language service API */
@ -1812,6 +1883,7 @@ declare namespace ts {
}
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@ -1836,6 +1908,7 @@ declare namespace ts {
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
interface LanguageService {
@ -1880,7 +1953,6 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {

File diff suppressed because it is too large Load Diff

View File

@ -167,163 +167,166 @@ declare namespace ts {
StringKeyword = 131,
SymbolKeyword = 132,
TypeKeyword = 133,
FromKeyword = 134,
GlobalKeyword = 135,
OfKeyword = 136,
QualifiedName = 137,
ComputedPropertyName = 138,
TypeParameter = 139,
Parameter = 140,
Decorator = 141,
PropertySignature = 142,
PropertyDeclaration = 143,
MethodSignature = 144,
MethodDeclaration = 145,
Constructor = 146,
GetAccessor = 147,
SetAccessor = 148,
CallSignature = 149,
ConstructSignature = 150,
IndexSignature = 151,
TypePredicate = 152,
TypeReference = 153,
FunctionType = 154,
ConstructorType = 155,
TypeQuery = 156,
TypeLiteral = 157,
ArrayType = 158,
TupleType = 159,
UnionType = 160,
IntersectionType = 161,
ParenthesizedType = 162,
ThisType = 163,
StringLiteralType = 164,
ObjectBindingPattern = 165,
ArrayBindingPattern = 166,
BindingElement = 167,
ArrayLiteralExpression = 168,
ObjectLiteralExpression = 169,
PropertyAccessExpression = 170,
ElementAccessExpression = 171,
CallExpression = 172,
NewExpression = 173,
TaggedTemplateExpression = 174,
TypeAssertionExpression = 175,
ParenthesizedExpression = 176,
FunctionExpression = 177,
ArrowFunction = 178,
DeleteExpression = 179,
TypeOfExpression = 180,
VoidExpression = 181,
AwaitExpression = 182,
PrefixUnaryExpression = 183,
PostfixUnaryExpression = 184,
BinaryExpression = 185,
ConditionalExpression = 186,
TemplateExpression = 187,
YieldExpression = 188,
SpreadElementExpression = 189,
ClassExpression = 190,
OmittedExpression = 191,
ExpressionWithTypeArguments = 192,
AsExpression = 193,
TemplateSpan = 194,
SemicolonClassElement = 195,
Block = 196,
VariableStatement = 197,
EmptyStatement = 198,
ExpressionStatement = 199,
IfStatement = 200,
DoStatement = 201,
WhileStatement = 202,
ForStatement = 203,
ForInStatement = 204,
ForOfStatement = 205,
ContinueStatement = 206,
BreakStatement = 207,
ReturnStatement = 208,
WithStatement = 209,
SwitchStatement = 210,
LabeledStatement = 211,
ThrowStatement = 212,
TryStatement = 213,
DebuggerStatement = 214,
VariableDeclaration = 215,
VariableDeclarationList = 216,
FunctionDeclaration = 217,
ClassDeclaration = 218,
InterfaceDeclaration = 219,
TypeAliasDeclaration = 220,
EnumDeclaration = 221,
ModuleDeclaration = 222,
ModuleBlock = 223,
CaseBlock = 224,
ImportEqualsDeclaration = 225,
ImportDeclaration = 226,
ImportClause = 227,
NamespaceImport = 228,
NamedImports = 229,
ImportSpecifier = 230,
ExportAssignment = 231,
ExportDeclaration = 232,
NamedExports = 233,
ExportSpecifier = 234,
MissingDeclaration = 235,
ExternalModuleReference = 236,
JsxElement = 237,
JsxSelfClosingElement = 238,
JsxOpeningElement = 239,
JsxText = 240,
JsxClosingElement = 241,
JsxAttribute = 242,
JsxSpreadAttribute = 243,
JsxExpression = 244,
CaseClause = 245,
DefaultClause = 246,
HeritageClause = 247,
CatchClause = 248,
PropertyAssignment = 249,
ShorthandPropertyAssignment = 250,
EnumMember = 251,
SourceFile = 252,
JSDocTypeExpression = 253,
JSDocAllType = 254,
JSDocUnknownType = 255,
JSDocArrayType = 256,
JSDocUnionType = 257,
JSDocTupleType = 258,
JSDocNullableType = 259,
JSDocNonNullableType = 260,
JSDocRecordType = 261,
JSDocRecordMember = 262,
JSDocTypeReference = 263,
JSDocOptionalType = 264,
JSDocFunctionType = 265,
JSDocVariadicType = 266,
JSDocConstructorType = 267,
JSDocThisType = 268,
JSDocComment = 269,
JSDocTag = 270,
JSDocParameterTag = 271,
JSDocReturnTag = 272,
JSDocTypeTag = 273,
JSDocTemplateTag = 274,
SyntaxList = 275,
Count = 276,
UndefinedKeyword = 134,
FromKeyword = 135,
GlobalKeyword = 136,
OfKeyword = 137,
QualifiedName = 138,
ComputedPropertyName = 139,
TypeParameter = 140,
Parameter = 141,
Decorator = 142,
PropertySignature = 143,
PropertyDeclaration = 144,
MethodSignature = 145,
MethodDeclaration = 146,
Constructor = 147,
GetAccessor = 148,
SetAccessor = 149,
CallSignature = 150,
ConstructSignature = 151,
IndexSignature = 152,
TypePredicate = 153,
TypeReference = 154,
FunctionType = 155,
ConstructorType = 156,
TypeQuery = 157,
TypeLiteral = 158,
ArrayType = 159,
TupleType = 160,
UnionType = 161,
IntersectionType = 162,
ParenthesizedType = 163,
ThisType = 164,
StringLiteralType = 165,
ObjectBindingPattern = 166,
ArrayBindingPattern = 167,
BindingElement = 168,
ArrayLiteralExpression = 169,
ObjectLiteralExpression = 170,
PropertyAccessExpression = 171,
ElementAccessExpression = 172,
CallExpression = 173,
NewExpression = 174,
TaggedTemplateExpression = 175,
TypeAssertionExpression = 176,
ParenthesizedExpression = 177,
FunctionExpression = 178,
ArrowFunction = 179,
DeleteExpression = 180,
TypeOfExpression = 181,
VoidExpression = 182,
AwaitExpression = 183,
PrefixUnaryExpression = 184,
PostfixUnaryExpression = 185,
BinaryExpression = 186,
ConditionalExpression = 187,
TemplateExpression = 188,
YieldExpression = 189,
SpreadElementExpression = 190,
ClassExpression = 191,
OmittedExpression = 192,
ExpressionWithTypeArguments = 193,
AsExpression = 194,
NonNullExpression = 195,
TemplateSpan = 196,
SemicolonClassElement = 197,
Block = 198,
VariableStatement = 199,
EmptyStatement = 200,
ExpressionStatement = 201,
IfStatement = 202,
DoStatement = 203,
WhileStatement = 204,
ForStatement = 205,
ForInStatement = 206,
ForOfStatement = 207,
ContinueStatement = 208,
BreakStatement = 209,
ReturnStatement = 210,
WithStatement = 211,
SwitchStatement = 212,
LabeledStatement = 213,
ThrowStatement = 214,
TryStatement = 215,
DebuggerStatement = 216,
VariableDeclaration = 217,
VariableDeclarationList = 218,
FunctionDeclaration = 219,
ClassDeclaration = 220,
InterfaceDeclaration = 221,
TypeAliasDeclaration = 222,
EnumDeclaration = 223,
ModuleDeclaration = 224,
ModuleBlock = 225,
CaseBlock = 226,
GlobalModuleExportDeclaration = 227,
ImportEqualsDeclaration = 228,
ImportDeclaration = 229,
ImportClause = 230,
NamespaceImport = 231,
NamedImports = 232,
ImportSpecifier = 233,
ExportAssignment = 234,
ExportDeclaration = 235,
NamedExports = 236,
ExportSpecifier = 237,
MissingDeclaration = 238,
ExternalModuleReference = 239,
JsxElement = 240,
JsxSelfClosingElement = 241,
JsxOpeningElement = 242,
JsxText = 243,
JsxClosingElement = 244,
JsxAttribute = 245,
JsxSpreadAttribute = 246,
JsxExpression = 247,
CaseClause = 248,
DefaultClause = 249,
HeritageClause = 250,
CatchClause = 251,
PropertyAssignment = 252,
ShorthandPropertyAssignment = 253,
EnumMember = 254,
SourceFile = 255,
JSDocTypeExpression = 256,
JSDocAllType = 257,
JSDocUnknownType = 258,
JSDocArrayType = 259,
JSDocUnionType = 260,
JSDocTupleType = 261,
JSDocNullableType = 262,
JSDocNonNullableType = 263,
JSDocRecordType = 264,
JSDocRecordMember = 265,
JSDocTypeReference = 266,
JSDocOptionalType = 267,
JSDocFunctionType = 268,
JSDocVariadicType = 269,
JSDocConstructorType = 270,
JSDocThisType = 271,
JSDocComment = 272,
JSDocTag = 273,
JSDocParameterTag = 274,
JSDocReturnTag = 275,
JSDocTypeTag = 276,
JSDocTemplateTag = 277,
SyntaxList = 278,
Count = 279,
FirstAssignment = 56,
LastAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 136,
LastKeyword = 137,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 152,
LastTypeNode = 164,
FirstTypeNode = 153,
LastTypeNode = 165,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstToken = 0,
LastToken = 136,
LastToken = 137,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
@ -332,7 +335,7 @@ declare namespace ts {
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 137,
FirstNode = 138,
}
enum NodeFlags {
None = 0,
@ -366,12 +369,13 @@ declare namespace ts {
JavaScriptFile = 134217728,
ThisNodeOrAnySubNodesHasError = 268435456,
HasAggregatedChildData = 536870912,
HasJsxSpreadAttribute = 1073741824,
Modifier = 959,
AccessibilityModifier = 28,
BlockScoped = 3072,
ReachabilityCheckFlags = 98304,
EmitHelperFlags = 3932160,
ContextFlags = 62914560,
ContextFlags = 197132288,
TypeExcludesFlags = 41943040,
}
enum JsxFlags {
@ -401,6 +405,9 @@ declare namespace ts {
text: string;
originalKeywordKind?: SyntaxKind;
}
interface TransientIdentifier extends Identifier {
resolvedSymbol: Symbol;
}
interface QualifiedName extends Node {
left: EntityName;
right: Identifier;
@ -702,6 +709,7 @@ declare namespace ts {
dotToken: Node;
name: Identifier;
}
type IdentifierOrPropertyAccess = Identifier | PropertyAccessExpression;
interface ElementAccessExpression extends MemberExpression {
expression: LeftHandSideExpression;
argumentExpression?: Expression;
@ -731,6 +739,9 @@ declare namespace ts {
expression: UnaryExpression;
}
type AssertionExpression = TypeAssertion | AsExpression;
interface NonNullExpression extends LeftHandSideExpression {
expression: Expression;
}
interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
@ -854,6 +865,7 @@ declare namespace ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
type DeclarationWithTypeParameters = SignatureDeclaration | ClassLikeDeclaration | InterfaceDeclaration | TypeAliasDeclaration;
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@ -923,6 +935,10 @@ declare namespace ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface GlobalModuleExportDeclaration extends DeclarationStatement {
name: Identifier;
moduleReference: LiteralLikeNode;
}
interface ExportDeclaration extends DeclarationStatement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
@ -1044,6 +1060,7 @@ declare namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
/**
@ -1066,7 +1083,7 @@ declare namespace ts {
readDirectory(rootDir: string, extension: string, exclude: string[]): string[];
}
interface WriteFileCallback {
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void, sourceFiles?: SourceFile[]): void;
}
class OperationCanceledException {
}
@ -1141,6 +1158,7 @@ declare namespace ts {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[];
}
interface TypeChecker {
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
@ -1186,7 +1204,7 @@ declare namespace ts {
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@ -1310,6 +1328,7 @@ declare namespace ts {
valueDeclaration?: Declaration;
members?: SymbolTable;
exports?: SymbolTable;
globalExports?: SymbolTable;
}
interface SymbolTable {
[index: string]: Symbol;
@ -1394,6 +1413,7 @@ declare namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType?: Type;
}
enum IndexKind {
String = 0,
@ -1442,10 +1462,12 @@ declare namespace ts {
type RootPaths = string[];
type PathSubstitutions = Map<string[]>;
type TsConfigOnlyOptions = RootPaths | PathSubstitutions;
type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions;
interface CompilerOptions {
allowNonTsExtensions?: boolean;
charset?: string;
declaration?: boolean;
declarationDir?: string;
diagnostics?: boolean;
emitBOM?: boolean;
help?: boolean;
@ -1455,6 +1477,7 @@ declare namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@ -1464,6 +1487,7 @@ declare namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@ -1492,11 +1516,30 @@ declare namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
[option: string]: string | number | boolean | TsConfigOnlyOptions;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
interface TypingOptions {
enableAutoDiscovery?: boolean;
include?: string[];
exclude?: string[];
[option: string]: string[] | boolean;
}
interface DiscoverTypingsInfo {
fileNames: string[];
projectRootPath: string;
safeListPath: string;
packageNameToTypingLocation: Map<string>;
typingOptions: TypingOptions;
compilerOptions: CompilerOptions;
}
enum ModuleKind {
None = 0,
@ -1540,6 +1583,7 @@ declare namespace ts {
}
interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
fileNames: string[];
errors: Diagnostic[];
}
@ -1557,16 +1601,29 @@ declare namespace ts {
resolvedModule: ResolvedModule;
failedLookupLocations: string[];
}
interface ResolvedTypeReferenceDirective {
primary: boolean;
resolvedFileName?: string;
}
interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* 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[];
}
interface TextSpan {
start: number;
@ -1578,8 +1635,8 @@ declare namespace ts {
}
}
declare namespace ts {
type FileWatcherCallback = (path: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (path: string) => void;
type FileWatcherCallback = (fileName: string, removed?: boolean) => void;
type DirectoryWatcherCallback = (directoryName: string) => void;
interface System {
args: string[];
newLine: string;
@ -1587,7 +1644,7 @@ declare namespace ts {
write(s: string): void;
readFile(path: string, encoding?: string): string;
writeFile(path: string, data: string, writeByteOrderMark?: boolean): void;
watchFile?(path: Path, callback: FileWatcherCallback): FileWatcher;
watchFile?(path: string, callback: FileWatcherCallback): FileWatcher;
watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher;
resolvePath(path: string): string;
fileExists(path: string): boolean;
@ -1596,6 +1653,8 @@ declare namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@ -1603,7 +1662,7 @@ declare namespace ts {
close(): void;
}
interface DirectoryWatcher extends FileWatcher {
directoryPath: Path;
directoryName: string;
referenceCount: number;
}
var sys: System;
@ -1685,17 +1744,26 @@ declare namespace ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean;
function startsWith(str: string, prefix: string): boolean;
function endsWith(str: string, suffix: string): boolean;
}
declare namespace ts {
function createNode(kind: SyntaxKind, pos?: number, end?: number): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean, scriptKind?: ScriptKind): SourceFile;
function isExternalModule(file: SourceFile): boolean;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare namespace ts {
const version: string;
function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string;
function resolveTripleslashReference(moduleName: string, containingFile: string): string;
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations;
function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations;
@ -1705,7 +1773,6 @@ declare namespace ts {
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program;
}
declare namespace ts {
function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine;
/**
* Read tsconfig.json file
* @param fileName The path to the config file
@ -1735,6 +1802,10 @@ declare namespace ts {
options: CompilerOptions;
errors: Diagnostic[];
};
function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): {
options: CompilerOptions;
errors: Diagnostic[];
};
}
declare namespace ts {
/** The version of the language service API */
@ -1812,6 +1883,7 @@ declare namespace ts {
}
interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@ -1836,6 +1908,7 @@ declare namespace ts {
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
interface LanguageService {
@ -1880,7 +1953,6 @@ declare namespace ts {
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion;
getEmitOutput(fileName: string): EmitOutput;
getProgram(): Program;
getSourceFile(fileName: string): SourceFile;
dispose(): void;
}
interface Classifications {

File diff suppressed because it is too large Load Diff

View File

@ -1,20 +0,0 @@
import * as Lint from "tslint/lib/lint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "Don't use the 'null' keyword - use 'undefined' for missing values instead";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NullWalker(sourceFile, this.getOptions()));
}
}
class NullWalker extends Lint.RuleWalker {
visitNode(node: ts.Node) {
super.visitNode(node);
if (node.kind === ts.SyntaxKind.NullKeyword) {
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
}
}
}

View File

@ -104,6 +104,7 @@ namespace ts {
function createBinder(): (file: SourceFile, options: CompilerOptions) => void {
let file: SourceFile;
let options: CompilerOptions;
let languageVersion: ScriptTarget;
let parent: Node;
let container: Node;
let blockScopeContainer: Node;
@ -122,6 +123,7 @@ namespace ts {
let hasAsyncFunctions: boolean;
let hasDecorators: boolean;
let hasParameterDecorators: boolean;
let hasJsxSpreadAttribute: boolean;
// 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
@ -135,6 +137,7 @@ namespace ts {
function bindSourceFile(f: SourceFile, opts: CompilerOptions) {
file = f;
options = opts;
languageVersion = getEmitScriptTarget(options);
inStrictMode = !!file.externalModuleIndicator;
classifiableNames = {};
@ -148,6 +151,7 @@ namespace ts {
file = undefined;
options = undefined;
languageVersion = undefined;
parent = undefined;
container = undefined;
blockScopeContainer = undefined;
@ -161,6 +165,7 @@ namespace ts {
hasAsyncFunctions = false;
hasDecorators = false;
hasParameterDecorators = false;
hasJsxSpreadAttribute = false;
}
return bindSourceFile;
@ -503,6 +508,9 @@ namespace ts {
if (hasAsyncFunctions) {
flags |= NodeFlags.HasAsyncFunctions;
}
if (hasJsxSpreadAttribute) {
flags |= NodeFlags.HasJsxSpreadAttribute;
}
}
node.flags = flags;
@ -1127,6 +1135,35 @@ namespace ts {
}
}
function getStrictModeBlockScopeFunctionDeclarationMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getContainingClass(node)) {
return 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 Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
}
return Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
}
function checkStrictModeFunctionDeclaration(node: FunctionDeclaration) {
if (languageVersion < ScriptTarget.ES6) {
// Report error if function is not top level function declaration
if (blockScopeContainer.kind !== SyntaxKind.SourceFile &&
blockScopeContainer.kind !== SyntaxKind.ModuleDeclaration &&
!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.
const errorSpan = getErrorSpanForNode(file, node);
file.bindDiagnostics.push(createFileDiagnostic(file, errorSpan.start, errorSpan.length,
getStrictModeBlockScopeFunctionDeclarationMessage(node)));
}
}
}
function checkStrictModeNumericLiteral(node: LiteralExpression) {
if (inStrictMode && node.isOctalLiteral) {
file.bindDiagnostics.push(createDiagnosticForNode(node, Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
@ -1306,6 +1343,10 @@ namespace ts {
case SyntaxKind.EnumMember:
return bindPropertyOrMethodOrAccessor(<Declaration>node, SymbolFlags.EnumMember, SymbolFlags.EnumMemberExcludes);
case SyntaxKind.JsxSpreadAttribute:
hasJsxSpreadAttribute = true;
return;
case SyntaxKind.CallSignature:
case SyntaxKind.ConstructSignature:
case SyntaxKind.IndexSignature:
@ -1641,7 +1682,13 @@ namespace ts {
}
checkStrictModeFunctionName(<FunctionDeclaration>node);
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
if (inStrictMode) {
checkStrictModeFunctionDeclaration(node);
return bindBlockScopedDeclaration(node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
else {
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.Function, SymbolFlags.FunctionExcludes);
}
}
function bindFunctionExpression(node: FunctionExpression) {

File diff suppressed because it is too large Load Diff

View File

@ -122,6 +122,11 @@ namespace ts {
type: "boolean",
description: Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
},
{
name: "noImplicitThis",
type: "boolean",
description: Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
},
{
name: "noLib",
type: "boolean",
@ -162,7 +167,6 @@ namespace ts {
},
{
name: "pretty",
paramType: Diagnostics.KIND,
description: Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental,
type: "boolean"
},
@ -313,9 +317,32 @@ namespace ts {
}
},
{
name: "traceModuleResolution",
name: "typesSearchPaths",
type: "list",
isTSConfigOnly: true,
element: {
name: "typesSearchPaths",
type: "string",
isFilePath: true
}
},
{
name: "typesRoot",
type: "string"
},
{
name: "types",
type: "list",
element: {
name: "types",
type: "string"
},
description: Diagnostics.Type_declaration_files_to_be_included_in_compilation
},
{
name: "traceResolution",
type: "boolean",
description: Diagnostics.Enable_tracing_of_the_module_resolution_process
description: Diagnostics.Enable_tracing_of_the_name_resolution_process
},
{
name: "allowJs",
@ -332,6 +359,41 @@ namespace ts {
type: "boolean",
description: Diagnostics.Do_not_emit_use_strict_directives_in_module_output
},
{
name: "listEmittedFiles",
type: "boolean"
},
{
name: "lib",
type: "list",
element: {
name: "lib",
type: {
// 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",
// Host only
"dom": "lib.dom.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"
},
},
description: Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon
},
{
name: "strictNullChecks",
type: "boolean",
@ -370,6 +432,7 @@ namespace ts {
}
let optionNameMapCache: OptionNameMap;
/* @internal */
export function getOptionNameMap(): OptionNameMap {
if (optionNameMapCache) {
@ -399,6 +462,32 @@ namespace ts {
return createCompilerDiagnostic(Diagnostics.Argument_for_0_option_must_be_Colon_1, `--${opt.name}`, namesOfType);
}
/* @internal */
export function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string, errors: Diagnostic[]) {
const key = (value || "").trim().toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
return map[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
/* @internal */
export function parseListTypeOption(opt: CommandLineOptionOfListType, value: string, errors: Diagnostic[]): (string | number)[] {
const values = (value || "").trim().split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
case "string":
return ts.map(values, v => v || "");
default:
return filter(map(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v, errors)), v => !!v);
}
}
/* @internal */
export function parseCommandLine(commandLine: string[], readFile?: (path: string) => string): ParsedCommandLine {
const options: CompilerOptions = {};
const fileNames: string[] = [];
@ -453,12 +542,12 @@ namespace ts {
i++;
break;
case "list":
options[opt.name] = parseListTypeOption(<CommandLineOptionOfListType>opt, args[i]);
options[opt.name] = parseListTypeOption(<CommandLineOptionOfListType>opt, args[i], errors);
i++;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
default:
options[opt.name] = parseCustomTypeOption(<CommandLineOptionOfCustomType>opt, args[i]);
options[opt.name] = parseCustomTypeOption(<CommandLineOptionOfCustomType>opt, args[i], errors);
i++;
break;
}
@ -471,29 +560,6 @@ namespace ts {
else {
fileNames.push(s);
}
function parseCustomTypeOption(opt: CommandLineOptionOfCustomType, value: string) {
const key = (value || "").trim().toLowerCase();
const map = opt.type;
if (hasProperty(map, key)) {
return map[key];
}
else {
errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
}
}
function parseListTypeOption(opt: CommandLineOptionOfListType, value: string): (string | number)[] {
const values = (value || "").trim().split(",");
switch (opt.element.type) {
case "number":
return ts.map(values, parseInt);
case "string":
return ts.map(values, v => v || "");
default:
return filter(map(values, v => parseCustomTypeOption(<CommandLineOptionOfCustomType>opt.element, v)), v => !!v);
}
}
}
}
@ -598,6 +664,7 @@ namespace ts {
const compilerOptions: CompilerOptions = convertCompilerOptionsFromJsonWorker(json["compilerOptions"], basePath, errors, configFileName);
const options = extend(existingOptions, compilerOptions);
const typingOptions: TypingOptions = convertTypingOptionsFromJsonWorker(json["typingOptions"], basePath, errors, configFileName);
options.configFilePath = configFileName;
const fileNames = getFileNames(errors);
@ -667,6 +734,9 @@ namespace ts {
}
}
}
if (hasProperty(json, "excludes") && !hasProperty(json, "exclude")) {
errors.push(createCompilerDiagnostic(Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
}
return fileNames;
}
}

View File

@ -15,7 +15,7 @@ namespace ts {
reportedDeclarationError: boolean;
moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[];
synchronousDeclarationOutput: string;
referencePathsOutput: string;
referencesOutput: string;
}
type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic;
@ -35,7 +35,7 @@ namespace ts {
forEachExpectedEmitFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile);
return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined);
function getDeclarationDiagnosticsFromFile({ declarationFilePath }, sources: SourceFile[], isBundledEmit: boolean) {
function getDeclarationDiagnosticsFromFile({ declarationFilePath }: EmitFileNames, sources: SourceFile[], isBundledEmit: boolean) {
emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit);
}
}
@ -73,7 +73,9 @@ namespace ts {
// 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
let referencePathsOutput = "";
let referencesOutput = "";
let usedTypeDirectiveReferences: Map<string>;
// Emit references corresponding to each file
const emittedReferencedFiles: SourceFile[] = [];
@ -153,11 +155,19 @@ namespace ts {
}
});
if (usedTypeDirectiveReferences) {
for (const directive in usedTypeDirectiveReferences) {
if (hasProperty(usedTypeDirectiveReferences, directive)) {
referencesOutput += `/// <reference types="${directive}" />${newLine}`;
}
}
}
return {
reportedDeclarationError,
moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo,
synchronousDeclarationOutput: writer.getText(),
referencePathsOutput,
referencesOutput,
};
function hasInternalAnnotation(range: CommentRange) {
@ -253,6 +263,21 @@ namespace ts {
setWriter(oldWriter);
}
function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[]): void {
if (!typeReferenceDirectives) {
return;
}
if (!usedTypeDirectiveReferences) {
usedTypeDirectiveReferences = {};
}
for (const directive of typeReferenceDirectives) {
if (!hasProperty(usedTypeDirectiveReferences, directive)) {
usedTypeDirectiveReferences[directive] = directive;
}
}
}
function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) {
if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) {
// write the aliases
@ -284,6 +309,7 @@ namespace ts {
function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) {
handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning));
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
}
function reportInaccessibleThisError() {
@ -420,6 +446,7 @@ namespace ts {
entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration);
handleSymbolAccessibilityError(visibilityResult);
recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
writeEntityName(entityName);
}
@ -530,7 +557,10 @@ namespace ts {
else {
// Expression
const tempVarName = getExportDefaultTempVariableName();
write("declare var ");
if (!noDeclare) {
write("declare ");
}
write("var ");
write(tempVarName);
write(": ");
writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic;
@ -1685,7 +1715,7 @@ namespace ts {
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ false);
referencePathsOutput += '/// <reference path="' + declFileName + '" />' + newLine;
referencesOutput += `/// <reference path="${declFileName}" />${newLine}`;
}
return addedBundledEmitReference;
@ -1707,7 +1737,7 @@ namespace ts {
const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit);
const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit;
if (!emitSkipped) {
const declarationOutput = emitDeclarationResult.referencePathsOutput
const declarationOutput = emitDeclarationResult.referencesOutput
+ getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo);
writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM);
}

View File

@ -811,10 +811,22 @@
"category": "Error",
"code": 1249
},
"'{0}' tag cannot be used independently as a top level JSDoc tag.": {
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'.": {
"category": "Error",
"code": 1250
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Class definitions are automatically in strict mode.": {
"category": "Error",
"code": 1251
},
"Function declarations are not allowed inside blocks in strict mode when targeting 'ES3' or 'ES5'. Modules are automatically in strict mode.": {
"category": "Error",
"code": 1252
},
"'{0}' tag cannot be used independently as a top level JSDoc tag.": {
"category": "Error",
"code": 1253
},
"'with' statements are not allowed in an async function block.": {
"category": "Error",
"code": 1300
@ -1051,7 +1063,7 @@
"category": "Error",
"code": 2351
},
"Neither type '{0}' nor type '{1}' is assignable to the other.": {
"Type '{0}' cannot be converted to type '{1}'.": {
"category": "Error",
"code": 2352
},
@ -1879,6 +1891,38 @@
"category": "Error",
"code": 2677
},
"Type '{0}' is not comparable to type '{1}'.": {
"category": "Error",
"code": 2678
},
"A function that is called with the 'new' keyword cannot have a 'this' type that is 'void'.": {
"category": "Error",
"code": 2679
},
"A 'this' parameter must be the first parameter.": {
"category": "Error",
"code": 2680
},
"A constructor cannot have a 'this' parameter.": {
"category": "Error",
"code": 2681
},
"A setter cannot have a 'this' parameter.": {
"category": "Error",
"code": 2682
},
"'this' implicitly has type 'any' because it does not have a type annotation.": {
"category": "Error",
"code": 2683
},
"The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'.": {
"category": "Error",
"code": 2684
},
"The 'this' types of each signature are incompatible.": {
"category": "Error",
"code": 2685
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@ -2159,6 +2203,11 @@
"category": "Error",
"code": 4082
},
"Conflicting library definitions for '{0}' found at '{1}' and '{2}'. Copy the correct file to the 'typings' folder to resolve this conflict.": {
"category": "Message",
"code": 4090
},
"The current host does not support the '{0}' option.": {
"category": "Error",
"code": 5001
@ -2492,6 +2541,10 @@
"category": "Message",
"code": 6078
},
"Specify library files to be included in the compilation: ": {
"category": "Message",
"code": 6079
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
@ -2508,7 +2561,7 @@
"category": "Message",
"code": 6084
},
"Enable tracing of the module resolution process.": {
"Enable tracing of the name resolution process.": {
"category": "Message",
"code": 6085
},
@ -2556,7 +2609,7 @@
"category": "Message",
"code": 6096
},
"File '{0}' exist - use it as a module resolution result.": {
"File '{0}' exist - use it as a name resolution result.": {
"category": "Message",
"code": 6097
},
@ -2568,11 +2621,11 @@
"category": "Message",
"code": 6099
},
"'package.json' does not have 'typings' field.": {
"'package.json' does not have 'types' field.": {
"category": "Message",
"code": 6100
},
"'package.json' has 'typings' field '{0}' that references '{1}'.": {
"'package.json' has '{0}' field '{1}' that references '{2}'.": {
"category": "Message",
"code": 6101
},
@ -2588,7 +2641,7 @@
"category": "Message",
"code": 6104
},
"Expected type of 'typings' field in 'package.json' to be 'string', got '{0}'.": {
"Expected type of '{0}' field in 'package.json' to be 'string', got '{1}'.": {
"category": "Message",
"code": 6105
},
@ -2624,7 +2677,66 @@
"category": "Message",
"code": 6113
},
"Unknown option 'excludes'. Did you mean 'exclude'?": {
"category": "Error",
"code": 6114
},
"Raise error on 'this' expressions with an implied 'any' type.": {
"category": "Message",
"code": 6115
},
"======== Resolving type reference directive '{0}', containing file '{1}', root directory '{2}'. ========": {
"category": "Message",
"code": 6116
},
"Resolving using primary search paths...": {
"category": "Message",
"code": 6117
},
"Resolving from node_modules folder...": {
"category": "Message",
"code": 6118
},
"======== Type reference directive '{0}' was successfully resolved to '{1}', primary: {2}. ========": {
"category": "Message",
"code": 6119
},
"======== Type reference directive '{0}' was not resolved. ========": {
"category": "Message",
"code": 6120
},
"Resolving with primary search path '{0}'": {
"category": "Message",
"code": 6121
},
"Root directory cannot be determined, skipping primary search paths.": {
"category": "Message",
"code": 6122
},
"======== Resolving type reference directive '{0}', containing file '{1}', root directory not set. ========": {
"category": "Message",
"code": 6123
},
"Type declaration files to be included in compilation.": {
"category": "Message",
"code": 6124
},
"Looking up in 'node_modules' folder, initial location '{0}'": {
"category": "Message",
"code": 6125
},
"Containing file is not specified and root directory cannot be determined, skipping lookup in 'node_modules' folder.": {
"category": "Message",
"code": 6126
},
"======== Resolving type reference directive '{0}', containing file not set, root directory '{1}'. ========": {
"category": "Message",
"code": 6127
},
"======== Resolving type reference directive '{0}', containing file not set, root directory not set. ========": {
"category": "Message",
"code": 6128
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005
@ -2713,6 +2825,10 @@
"category": "Error",
"code": 7030
},
"Binding element '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7031
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000

View File

@ -345,6 +345,16 @@ var __extends = (this && this.__extends) || function (d, b) {
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};`;
const assignHelper = `
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};`;
// emit output for the __decorate helper function
const decorateHelper = `
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
@ -380,6 +390,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
const languageVersion = getEmitScriptTarget(compilerOptions);
const modulekind = getEmitModuleKind(compilerOptions);
const sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
const emittedFilesList: string[] = compilerOptions.listEmittedFiles ? [] : undefined;
const emitterDiagnostics = createDiagnosticCollection();
let emitSkipped = false;
const newLine = host.getNewLine();
@ -390,6 +401,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
return {
emitSkipped,
diagnostics: emitterDiagnostics.getDiagnostics(),
emittedFiles: emittedFilesList,
sourceMaps: sourceMapDataList
};
@ -540,6 +552,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
let convertedLoopState: ConvertedLoopState;
let extendsEmitted: boolean;
let assignEmitted: boolean;
let decorateEmitted: boolean;
let paramEmitted: boolean;
let awaiterEmitted: boolean;
@ -623,6 +636,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
decorateEmitted = false;
paramEmitted = false;
awaiterEmitted = false;
assignEmitted = false;
tempFlags = 0;
tempVariables = undefined;
tempParameters = undefined;
@ -1259,11 +1273,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
else {
// Either emit one big object literal (no spread attribs), or
// a call to React.__spread
// a call to the __assign helper
const attrs = openingNode.attributes;
if (forEach(attrs, attr => attr.kind === SyntaxKind.JsxSpreadAttribute)) {
emitExpressionIdentifier(syntheticReactRef);
write(".__spread(");
write("__assign(");
let haveOpenedObjectLiteral = false;
for (let i = 0; i < attrs.length; i++) {
@ -4609,7 +4622,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
}
emitEnd(node);
if (kind !== SyntaxKind.MethodDeclaration && kind !== SyntaxKind.MethodSignature) {
if (kind !== SyntaxKind.MethodDeclaration &&
kind !== SyntaxKind.MethodSignature &&
kind !== SyntaxKind.ArrowFunction) {
emitTrailingComments(node);
}
}
@ -4628,8 +4643,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
write("(");
if (node) {
const parameters = node.parameters;
const skipCount = node.parameters.length && (<Identifier>node.parameters[0].name).text === "this" ? 1 : 0;
const omitCount = languageVersion < ScriptTarget.ES6 && hasRestParameter(node) ? 1 : 0;
emitList(parameters, 0, parameters.length - omitCount, /*multiLine*/ false, /*trailingComma*/ false);
emitList(parameters, skipCount, parameters.length - omitCount - skipCount, /*multiLine*/ false, /*trailingComma*/ false);
}
write(")");
decreaseIndent();
@ -7649,7 +7665,7 @@ const _super = (function (geti, seti) {
}
function isUseStrictPrologue(node: ExpressionStatement): boolean {
return !!(node.expression as StringLiteral).text.match(/use strict/);
return (node.expression as StringLiteral).text === "use strict";
}
function ensureUseStrictPrologue(startWithNewLine: boolean, writeUseStrict: boolean) {
@ -7699,11 +7715,16 @@ const _super = (function (geti, seti) {
if (!compilerOptions.noEmitHelpers) {
// Only Emit __extends function when target ES5.
// For target ES6 and above, we can emit classDeclaration as is.
if ((languageVersion < ScriptTarget.ES6) && (!extendsEmitted && node.flags & NodeFlags.HasClassExtends)) {
if (languageVersion < ScriptTarget.ES6 && !extendsEmitted && node.flags & NodeFlags.HasClassExtends) {
writeLines(extendsHelper);
extendsEmitted = true;
}
if (compilerOptions.jsx !== JsxEmit.Preserve && !assignEmitted && (node.flags & NodeFlags.HasJsxSpreadAttribute)) {
writeLines(assignHelper);
assignEmitted = true;
}
if (!decorateEmitted && node.flags & NodeFlags.HasDecorators) {
writeLines(decorateHelper);
if (compilerOptions.emitDecoratorMetadata) {
@ -8230,6 +8251,16 @@ const _super = (function (geti, seti) {
if (declarationFilePath) {
emitSkipped = writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped;
}
if (!emitSkipped && emittedFilesList) {
emittedFilesList.push(jsFilePath);
if (sourceMapFilePath) {
emittedFilesList.push(sourceMapFilePath);
}
if (declarationFilePath) {
emittedFilesList.push(declarationFilePath);
}
}
}
}
}

View File

@ -2025,7 +2025,7 @@ namespace ts {
}
function isStartOfParameter(): boolean {
return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken;
return token === SyntaxKind.DotDotDotToken || isIdentifierOrPattern() || isModifierKind(token) || token === SyntaxKind.AtToken || token === SyntaxKind.ThisKeyword;
}
function setModifiers(node: Node, modifiers: ModifiersArray) {
@ -2037,15 +2037,19 @@ namespace ts {
function parseParameter(): ParameterDeclaration {
const node = <ParameterDeclaration>createNode(SyntaxKind.Parameter);
if (token === SyntaxKind.ThisKeyword) {
node.name = createIdentifier(/*isIdentifier*/true, undefined);
node.type = parseParameterType();
return finishNode(node);
}
node.decorators = parseDecorators();
setModifiers(node, parseModifiers());
node.dotDotDotToken = parseOptionalToken(SyntaxKind.DotDotDotToken);
// FormalParameter [Yield,Await]:
// BindingElement[?Yield,?Await]
node.name = parseIdentifierOrPattern();
if (getFullWidth(node.name) === 0 && node.flags === 0 && isModifierKind(token)) {
// in cases like
// 'use strict'
@ -2488,7 +2492,7 @@ namespace ts {
// Skip modifiers
parseModifiers();
}
if (isIdentifier()) {
if (isIdentifier() || token === SyntaxKind.ThisKeyword) {
nextToken();
return true;
}
@ -5520,6 +5524,7 @@ namespace ts {
function processReferenceComments(sourceFile: SourceFile): void {
const triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText);
const referencedFiles: FileReference[] = [];
const typeReferenceDirectives: FileReference[] = [];
const amdDependencies: { path: string; name: string }[] = [];
let amdModuleName: string;
@ -5546,7 +5551,12 @@ namespace ts {
sourceFile.hasNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
const diagnosticMessage = referencePathMatchResult.diagnosticMessage;
if (fileReference) {
referencedFiles.push(fileReference);
if (referencePathMatchResult.isTypeReferenceDirective) {
typeReferenceDirectives.push(fileReference);
}
else {
referencedFiles.push(fileReference);
}
}
if (diagnosticMessage) {
parseDiagnostics.push(createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, diagnosticMessage));
@ -5578,6 +5588,7 @@ namespace ts {
}
sourceFile.referencedFiles = referencedFiles;
sourceFile.typeReferenceDirectives = typeReferenceDirectives;
sourceFile.amdDependencies = amdDependencies;
sourceFile.moduleName = amdModuleName;
}

View File

@ -12,11 +12,17 @@ namespace ts {
const emptyArray: any[] = [];
const defaultLibrarySearchPaths = [
"types/",
"node_modules/",
"node_modules/@types/",
];
export const version = "1.9.0";
export function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean): string {
let fileName = "tsconfig.json";
while (true) {
const fileName = combinePaths(searchPath, "tsconfig.json");
if (fileExists(fileName)) {
return fileName;
}
@ -25,7 +31,6 @@ namespace ts {
break;
}
searchPath = parentPath;
fileName = "../" + fileName;
}
return undefined;
}
@ -36,22 +41,58 @@ namespace ts {
return normalizePath(referencedFileName);
}
/* @internal */
export function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string {
let commonPathComponents: string[];
const failed = forEach(fileNames, sourceFile => {
// Each file contributes into common source file path
const sourcePathComponents = getNormalizedPathComponents(sourceFile, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); 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 getNormalizedPathFromPathComponents(commonPathComponents);
}
function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void;
function trace(host: ModuleResolutionHost, message: DiagnosticMessage): void {
host.trace(formatMessage.apply(undefined, arguments));
}
function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean {
return compilerOptions.traceModuleResolution && host.trace !== undefined;
}
function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
return compilerOptions.traceResolution && host.trace !== undefined;
}
function hasZeroOrOneAsteriskCharacter(str: string): boolean {
@ -92,6 +133,160 @@ namespace ts {
skipTsx: boolean;
}
function tryReadTypesSection(packageJsonPath: string, baseDirectory: string, state: ModuleResolutionState): string {
let jsonContent: { typings?: string, types?: string };
try {
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string, types?: string }>JSON.parse(jsonText) : {};
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = {};
}
let typesFile: string;
let fieldName: string;
// first try to read content of 'typings' section (backward compatibility)
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
fieldName = "typings";
typesFile = jsonContent.typings;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "typings", typeof jsonContent.typings);
}
}
}
// then read 'types'
if (!typesFile && jsonContent.types) {
if (typeof jsonContent.types === "string") {
fieldName = "types";
typesFile = jsonContent.types;
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, "types", typeof jsonContent.types);
}
}
}
if (typesFile) {
const typesFilePath = normalizePath(combinePaths(baseDirectory, typesFile));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath);
}
return typesFilePath;
}
return undefined;
}
const typeReferenceExtensions = [".d.ts"];
/**
* @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
* This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
* is assumed to be the same as root directory of the project.
*/
export function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(options, host);
const moduleResolutionState: ModuleResolutionState = {
compilerOptions: options,
host: host,
skipTsx: true,
traceEnabled
};
// use typesRoot and fallback to directory that contains tsconfig if typesRoot is not set
const rootDir = options.typesRoot || (options.configFilePath ? getDirectoryPath(options.configFilePath) : undefined);
if (traceEnabled) {
if (containingFile === undefined) {
if (rootDir === undefined) {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
}
else {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, rootDir);
}
}
else {
if (rootDir === undefined) {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
}
else {
trace(host, Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, rootDir);
}
}
}
const failedLookupLocations: string[] = [];
// Check primary library paths
if (rootDir !== undefined) {
const effectivePrimarySearchPaths = options.typesSearchPaths || defaultLibrarySearchPaths;
for (const searchPath of effectivePrimarySearchPaths) {
const primaryPath = combinePaths(rootDir, searchPath);
if (traceEnabled) {
trace(host, Diagnostics.Resolving_with_primary_search_path_0, primaryPath);
}
const candidate = combinePaths(primaryPath, typeReferenceDirectiveName);
const candidateDirectory = getDirectoryPath(candidate);
const resolvedFile = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations,
!directoryProbablyExists(candidateDirectory, host), moduleResolutionState);
if (resolvedFile) {
if (traceEnabled) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, true);
}
return {
resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile },
failedLookupLocations
};
}
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
}
}
let resolvedFile: string;
let initialLocationForSecondaryLookup: string;
if (containingFile) {
initialLocationForSecondaryLookup = getDirectoryPath(containingFile);
}
else {
initialLocationForSecondaryLookup = rootDir;
}
if (initialLocationForSecondaryLookup !== undefined) {
// check secondary locations
if (traceEnabled) {
trace(host, Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
}
resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState);
if (traceEnabled) {
if (resolvedFile) {
trace(host, Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false);
}
else {
trace(host, Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
}
}
}
else {
if (traceEnabled) {
trace(host, Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
}
}
return {
resolvedTypeReferenceDirective: resolvedFile
? { primary: false, resolvedFileName: resolvedFile }
: undefined,
failedLookupLocations
};
}
export function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations {
const traceEnabled = isTraceEnabled(compilerOptions, host);
if (traceEnabled) {
@ -371,7 +566,7 @@ namespace ts {
const traceEnabled = isTraceEnabled(compilerOptions, host);
const failedLookupLocations: string[] = [];
const state = {compilerOptions, host, traceEnabled, skipTsx: false};
const state = { compilerOptions, host, traceEnabled, skipTsx: false };
let resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName,
failedLookupLocations, supportedExtensions, state);
@ -407,7 +602,7 @@ namespace ts {
}
/* @internal */
export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean } ): boolean {
export function directoryProbablyExists(directoryName: string, host: { directoryExists?: (directoryName: string) => boolean }): boolean {
// if host does not support 'directoryExists' assume that directory will exist
return !host.directoryExists || host.directoryExists(directoryName);
}
@ -417,6 +612,13 @@ namespace 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(candidate: string, extensions: string[], failedLookupLocation: string[], onlyRecordFailures: boolean, state: ModuleResolutionState): string {
if (!onlyRecordFailures) {
// check if containig folder exists - if it doesn't then just record failures for all supported extensions without disk probing
const directory = getDirectoryPath(candidate);
if (directory) {
onlyRecordFailures = !directoryProbablyExists(directory, state.host);
}
}
return forEach(extensions, tryLoad);
function tryLoad(ext: string): string {
@ -426,7 +628,7 @@ namespace ts {
const fileName = fileExtensionIs(candidate, ext) ? candidate : candidate + ext;
if (!onlyRecordFailures && state.host.fileExists(fileName)) {
if (state.traceEnabled) {
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_module_resolution_result, fileName);
trace(state.host, Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
}
return fileName;
}
@ -447,36 +649,16 @@ namespace ts {
if (state.traceEnabled) {
trace(state.host, Diagnostics.Found_package_json_at_0, packageJsonPath);
}
let jsonContent: { typings?: string };
try {
const jsonText = state.host.readFile(packageJsonPath);
jsonContent = jsonText ? <{ typings?: string }>JSON.parse(jsonText) : { typings: undefined };
}
catch (e) {
// gracefully handle if readFile fails or returns not JSON
jsonContent = { typings: undefined };
}
if (jsonContent.typings) {
if (typeof jsonContent.typings === "string") {
const typingsFile = normalizePath(combinePaths(candidate, jsonContent.typings));
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_has_typings_field_0_that_references_1, jsonContent.typings, typingsFile);
}
const result = loadModuleFromFile(typingsFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typingsFile), state.host), state);
if (result) {
return result;
}
}
else if (state.traceEnabled) {
trace(state.host, Diagnostics.Expected_type_of_typings_field_in_package_json_to_be_string_got_0, typeof jsonContent.typings);
const typesFile = tryReadTypesSection(packageJsonPath, candidate, state);
if (typesFile) {
const result = loadModuleFromFile(typesFile, extensions, failedLookupLocation, !directoryProbablyExists(getDirectoryPath(typesFile), state.host), state);
if (result) {
return result;
}
}
else {
if (state.traceEnabled) {
trace(state.host, Diagnostics.package_json_does_not_have_typings_field);
trace(state.host, Diagnostics.package_json_does_not_have_types_field);
}
}
}
@ -491,20 +673,31 @@ namespace ts {
return loadModuleFromFile(combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state);
}
function loadModuleFromNodeModulesFolder(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
// Load only typescript files irrespective of allowJs option if loading from node modules
let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
}
function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState): string {
directory = normalizeSlashes(directory);
while (true) {
const baseName = getBaseFileName(directory);
if (baseName !== "node_modules") {
const nodeModulesFolder = combinePaths(directory, "node_modules");
const nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host);
const candidate = normalizePath(combinePaths(nodeModulesFolder, moduleName));
// Load only typescript files irrespective of allowJs option if loading from node modules
let result = loadModuleFromFile(candidate, supportedTypeScriptExtensions, failedLookupLocations, !nodeModulesFolderExists, state);
if (result) {
return result;
}
result = loadNodeModuleFromDirectory(supportedTypeScriptExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state);
const result =
// first: try to load module as-is
loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) ||
// second: try to load module from the scope '@types'
loadModuleFromNodeModulesFolder(combinePaths("@types", moduleName), directory, failedLookupLocations, state);
if (result) {
return result;
}
@ -554,7 +747,7 @@ namespace ts {
return referencedSourceFile
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations }
: { resolvedModule: undefined, failedLookupLocations };
}
@ -566,6 +759,12 @@ namespace ts {
sourceMap: false,
};
interface OutputFingerprint {
hash: string;
byteOrderMark: boolean;
mtime: Date;
}
export function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost {
const existingDirectories: Map<boolean> = {};
@ -616,11 +815,50 @@ namespace ts {
}
}
let outputFingerprints: Map<OutputFingerprint>;
function writeFileIfUpdated(fileName: string, data: string, writeByteOrderMark: boolean): void {
if (!outputFingerprints) {
outputFingerprints = {};
}
const hash = sys.createHash(data);
const mtimeBefore = sys.getModifiedTime(fileName);
if (mtimeBefore && hasProperty(outputFingerprints, fileName)) {
const fingerprint = outputFingerprints[fileName];
// If output has not been changed, and the file has no external modification
if (fingerprint.byteOrderMark === writeByteOrderMark &&
fingerprint.hash === hash &&
fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
return;
}
}
sys.writeFile(fileName, data, writeByteOrderMark);
const mtimeAfter = sys.getModifiedTime(fileName);
outputFingerprints[fileName] = {
hash,
byteOrderMark: writeByteOrderMark,
mtime: mtimeAfter
};
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
try {
const start = new Date().getTime();
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
if (isWatchSet(options) && sys.createHash && sys.getModifiedTime) {
writeFileIfUpdated(fileName, data, writeByteOrderMark);
}
else {
sys.writeFile(fileName, data, writeByteOrderMark);
}
ioWriteTime += new Date().getTime() - start;
}
catch (e) {
@ -630,11 +868,16 @@ namespace ts {
}
}
function getDefaultLibLocation(): string {
return getDirectoryPath(normalizePath(sys.getExecutingFilePath()));
}
const newLine = getNewLineCharacter(options);
return {
getSourceFile,
getDefaultLibFileName: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), getDefaultLibFileName(options)),
getDefaultLibLocation,
getDefaultLibFileName: options => combinePaths(getDefaultLibLocation(), getDefaultLibFileName(options)),
writeFile,
getCurrentDirectory: memoize(() => sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
@ -649,9 +892,9 @@ namespace ts {
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[] {
let diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
program.getSyntacticDiagnostics(sourceFile, cancellationToken),
program.getGlobalDiagnostics(cancellationToken),
program.getSemanticDiagnostics(sourceFile, cancellationToken));
if (program.getCompilerOptions().declaration) {
diagnostics = diagnostics.concat(program.getDeclarationDiagnostics(sourceFile, cancellationToken));
@ -686,75 +929,98 @@ namespace ts {
}
}
function loadWithLocalCache<T>(names: string[], containingFile: string, loader: (name: string, containingFile: string) => T): T[] {
if (names.length === 0) {
return [];
}
const resolutions: T[] = [];
const cache: Map<T> = {};
for (const name of names) {
let result: T;
if (hasProperty(cache, name)) {
result = cache[name];
}
else {
result = loader(name, containingFile);
cache[name] = result;
}
resolutions.push(result);
}
return resolutions;
}
export function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program {
let program: Program;
let files: SourceFile[] = [];
let fileProcessingDiagnostics = createDiagnosticCollection();
const programDiagnostics = createDiagnosticCollection();
let commonSourceDirectory: string;
let diagnosticsProducingTypeChecker: TypeChecker;
let noDiagnosticsTypeChecker: TypeChecker;
let classifiableNames: Map<string>;
let skipDefaultLib = options.noLib;
const supportedExtensions = getSupportedExtensions(options);
let resolvedTypeReferenceDirectives: Map<ResolvedTypeReferenceDirective> = {};
let fileProcessingDiagnostics = createDiagnosticCollection();
const start = new Date().getTime();
host = host || createCompilerHost(options);
let skipDefaultLib = options.noLib;
const programDiagnostics = createDiagnosticCollection();
const currentDirectory = host.getCurrentDirectory();
const supportedExtensions = getSupportedExtensions(options);
// Map storing if there is emit blocking diagnostics for given input
const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName);
const currentDirectory = host.getCurrentDirectory();
const resolveModuleNamesWorker = host.resolveModuleNames
? ((moduleNames: string[], containingFile: string) => host.resolveModuleNames(moduleNames, containingFile))
: ((moduleNames: string[], containingFile: string) => {
const resolvedModuleNames: ResolvedModule[] = [];
// resolveModuleName does not store any results between calls.
// lookup is a local cache to avoid resolving the same module name several times
const lookup: Map<ResolvedModule> = {};
for (const moduleName of moduleNames) {
let resolvedName: ResolvedModule;
if (hasProperty(lookup, moduleName)) {
resolvedName = lookup[moduleName];
}
else {
resolvedName = resolveModuleName(moduleName, containingFile, options, host).resolvedModule;
lookup[moduleName] = resolvedName;
}
resolvedModuleNames.push(resolvedName);
}
return resolvedModuleNames;
});
let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string) => ResolvedModule[];
if (host.resolveModuleNames) {
resolveModuleNamesWorker = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile);
}
else {
const loader = (moduleName: string, containingFile: string) => resolveModuleName(moduleName, containingFile, options, host).resolvedModule;
resolveModuleNamesWorker = (moduleNames, containingFile) => loadWithLocalCache(moduleNames, containingFile, loader);
}
let resolveTypeReferenceDirectiveNamesWorker: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[];
if (host.resolveTypeReferenceDirectives) {
resolveTypeReferenceDirectiveNamesWorker = (typeDirectiveNames, containingFile) => host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile);
}
else {
const loader = (typesRef: string, containingFile: string) => resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective;
resolveTypeReferenceDirectiveNamesWorker = (typeReferenceDirectiveNames, containingFile) => loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader);
}
const filesByName = createFileMap<SourceFile>();
// stores 'filename -> file association' ignoring case
// used to track cases when two file names differ only in casing
const filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? createFileMap<SourceFile>(fileName => fileName.toLowerCase()) : undefined;
if (oldProgram) {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
const oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx) ||
(oldOptions.allowJs !== options.allowJs)) {
oldProgram = undefined;
}
}
if (!tryReuseStructureFromOldProgram()) {
// load type declarations specified via 'types' argument
if (options.types && options.types.length) {
const resolutions = resolveTypeReferenceDirectiveNamesWorker(options.types, /*containingFile*/ undefined);
for (let i = 0; i < options.types.length; i++) {
processTypeReferenceDirective(options.types[i], resolutions[i]);
}
}
forEach(rootNames, name => processRootFile(name, /*isDefaultLib*/ false));
// 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) {
processRootFile(host.getDefaultLibFileName(options), /*isDefaultLib*/ true);
// 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(host.getDefaultLibFileName(options), /*isDefaultLib*/ true);
}
else {
const libDirectory = host.getDefaultLibLocation ? host.getDefaultLibLocation() : getDirectoryPath(host.getDefaultLibFileName(options));
forEach(options.lib, libFileName => {
processRootFile(combinePaths(libDirectory, libFileName), /*isDefaultLib*/ true);
});
}
}
}
@ -781,7 +1047,8 @@ namespace ts {
getIdentifierCount: () => getDiagnosticsProducingTypeChecker().getIdentifierCount(),
getSymbolCount: () => getDiagnosticsProducingTypeChecker().getSymbolCount(),
getTypeCount: () => getDiagnosticsProducingTypeChecker().getTypeCount(),
getFileProcessingDiagnostics: () => fileProcessingDiagnostics
getFileProcessingDiagnostics: () => fileProcessingDiagnostics,
getResolvedTypeReferenceDirectives: () => resolvedTypeReferenceDirectives
};
verifyCompilerOptions();
@ -828,6 +1095,21 @@ namespace ts {
return false;
}
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
const oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx) ||
(oldOptions.allowJs !== options.allowJs) ||
(oldOptions.rootDir !== options.rootDir) ||
(oldOptions.typesSearchPaths !== options.typesSearchPaths) ||
(oldOptions.configFilePath !== options.configFilePath)) {
return false;
}
Debug.assert(!oldProgram.structureIsReused);
// there is an old program, check if we can reuse its structure
@ -836,6 +1118,10 @@ namespace ts {
return false;
}
if (!arrayIsEqualTo(options.types, oldOptions.types)) {
return false;
}
// check if program source files has changed in the way that can affect structure of the program
const newSourceFiles: SourceFile[] = [];
const filePaths: Path[] = [];
@ -874,26 +1160,33 @@ namespace ts {
return false;
}
if (!arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
// 'types' references has changed
return false;
}
const newSourceFilePath = getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory);
if (resolveModuleNamesWorker) {
const moduleNames = map(concatenate(newSourceFile.imports, newSourceFile.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(newSourceFile.fileName, currentDirectory));
const resolutions = resolveModuleNamesWorker(moduleNames, newSourceFilePath);
// ensure that module resolution results are still correct
for (let i = 0; i < moduleNames.length; i++) {
const newResolution = resolutions[i];
const oldResolution = getResolvedModule(oldSourceFile, moduleNames[i]);
const resolutionChanged = oldResolution
? !newResolution ||
oldResolution.resolvedFileName !== newResolution.resolvedFileName ||
!!oldResolution.isExternalLibraryImport !== !!newResolution.isExternalLibraryImport
: newResolution;
if (resolutionChanged) {
return false;
}
const resolutionsChanged = hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, moduleResolutionIsEqualTo);
if (resolutionsChanged) {
return false;
}
}
// pass the cache of module resolutions from the old source file
if (resolveTypeReferenceDirectiveNamesWorker) {
const typesReferenceDirectives = map(newSourceFile.typeReferenceDirectives, x => x.fileName);
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFilePath);
// ensure that types resolutions are still correct
const resolutionsChanged = hasChangesInResolutions(typesReferenceDirectives, resolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, typeDirectiveIsEqualTo);
if (resolutionsChanged) {
return false;
}
}
// pass the cache of module/types resolutions from the old source file
newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
modifiedSourceFiles.push(newSourceFile);
}
else {
@ -916,6 +1209,7 @@ namespace ts {
for (const modifiedFile of modifiedSourceFiles) {
fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile);
}
resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
oldProgram.structureIsReused = true;
return true;
@ -956,7 +1250,7 @@ namespace ts {
let declarationDiagnostics: Diagnostic[] = [];
if (options.noEmit) {
return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emitSkipped: true };
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,
@ -976,6 +1270,7 @@ namespace ts {
return {
diagnostics: concatenate(diagnostics, declarationDiagnostics),
sourceMaps: undefined,
emittedFiles: undefined,
emitSkipped: true
};
}
@ -1007,9 +1302,9 @@ namespace ts {
}
function getDiagnosticsHelper(
sourceFile: SourceFile,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[],
cancellationToken: CancellationToken): Diagnostic[] {
sourceFile: SourceFile,
getDiagnostics: (sourceFile: SourceFile, cancellationToken: CancellationToken) => Diagnostic[],
cancellationToken: CancellationToken): Diagnostic[] {
if (sourceFile) {
return getDiagnostics(sourceFile, cancellationToken);
}
@ -1483,7 +1778,8 @@ namespace ts {
const basePath = getDirectoryPath(fileName);
if (!options.noResolve) {
processReferencedFiles(file, basePath);
processReferencedFiles(file, basePath, isDefaultLib);
processTypeReferenceDirectives(file);
}
// always process imported modules to record module name resolutions
@ -1500,13 +1796,80 @@ namespace ts {
return file;
}
function processReferencedFiles(file: SourceFile, basePath: string) {
function processReferencedFiles(file: SourceFile, basePath: string, isDefaultLib: boolean) {
forEach(file.referencedFiles, ref => {
const referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
processSourceFile(referencedFileName, /*isDefaultLib*/ false, /*isReference*/ true, file, ref.pos, ref.end);
processSourceFile(referencedFileName, isDefaultLib, /*isReference*/ true, file, ref.pos, ref.end);
});
}
function processTypeReferenceDirectives(file: SourceFile) {
const typeDirectives = map(file.typeReferenceDirectives, l => l.fileName);
const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file.fileName);
for (let i = 0; i < typeDirectives.length; i++) {
const ref = file.typeReferenceDirectives[i];
const resolvedTypeReferenceDirective = resolutions[i];
// store resolved type directive on the file
setResolvedTypeReferenceDirective(file, ref.fileName, resolvedTypeReferenceDirective);
processTypeReferenceDirective(ref.fileName, resolvedTypeReferenceDirective, file, ref.pos, ref.end);
}
}
function processTypeReferenceDirective(typeReferenceDirective: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective,
refFile?: SourceFile, refPos?: number, refEnd?: number): void {
// If we already found this library as a primary reference - nothing to do
const previousResolution = resolvedTypeReferenceDirectives[typeReferenceDirective];
if (previousResolution && previousResolution.primary) {
return;
}
let saveResolution = true;
if (resolvedTypeReferenceDirective) {
if (resolvedTypeReferenceDirective.primary) {
// resolved from the primary path
processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*isReference*/ true, 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) {
const otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
if (otherFileText !== getSourceFile(previousResolution.resolvedFileName).text) {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd,
Diagnostics.Conflicting_library_definitions_for_0_found_at_1_and_2_Copy_the_correct_file_to_the_typings_folder_to_resolve_this_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, /*isReference*/ true, refFile, refPos, refEnd);
}
}
}
else {
fileProcessingDiagnostics.add(createDiagnostic(refFile, refPos, refEnd, Diagnostics.Cannot_find_name_0, typeReferenceDirective));
}
if (saveResolution) {
resolvedTypeReferenceDirectives[typeReferenceDirective] = resolvedTypeReferenceDirective;
}
}
function createDiagnostic(refFile: SourceFile, refPos: number, refEnd: number, message: DiagnosticMessage, ...args: any[]): Diagnostic {
if (refFile === undefined || refPos === undefined || refEnd === undefined) {
return createCompilerDiagnostic(message, ...args);
}
else {
return createFileDiagnostic(refFile, refPos, refEnd - refPos, message, ...args);
}
}
function getCanonicalFileName(fileName: string): string {
return host.getCanonicalFileName(fileName);
}
@ -1554,51 +1917,13 @@ namespace ts {
}
function computeCommonSourceDirectory(sourceFiles: SourceFile[]): string {
let commonPathComponents: string[];
const failed = forEach(files, sourceFile => {
// Each file contributes into common source file path
if (isDeclarationFile(sourceFile)) {
return;
const fileNames: string[] = [];
for (const file of sourceFiles) {
if (!file.isDeclarationFile) {
fileNames.push(file.fileName);
}
const sourcePathComponents = getNormalizedPathComponents(sourceFile.fileName, currentDirectory);
sourcePathComponents.pop(); // The base file name is not part of the common directory path
if (!commonPathComponents) {
// first file
commonPathComponents = sourcePathComponents;
return;
}
for (let i = 0, n = Math.min(commonPathComponents.length, sourcePathComponents.length); 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 getNormalizedPathFromPathComponents(commonPathComponents);
return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
}
function checkSourceFilesBelongToPath(sourceFiles: SourceFile[], rootDirectory: string): boolean {
@ -1700,6 +2025,10 @@ namespace ts {
}
}
if (options.lib && options.noLib) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib"));
}
const languageVersion = options.target || ScriptTarget.ES3;
const outFile = options.outFile || options.out;
@ -1742,7 +2071,7 @@ namespace ts {
// 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 === "" && forEach(files, file => getRootLength(file.fileName) > 1)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
}
}

View File

@ -20,6 +20,8 @@ namespace ts {
getExecutingFilePath(): string;
getCurrentDirectory(): string;
readDirectory(path: string, extension?: string, exclude?: string[]): string[];
getModifiedTime?(path: string): Date;
createHash?(data: string): string;
getMemoryUsage?(): number;
exit(exitCode?: number): void;
}
@ -226,6 +228,7 @@ namespace ts {
const _fs = require("fs");
const _path = require("path");
const _os = require("os");
const _crypto = require("crypto");
// average async stat takes about 30 microseconds
// set chunk size to do 30 files in < 1 millisecond
@ -584,6 +587,19 @@ namespace ts {
return process.cwd();
},
readDirectory,
getModifiedTime(path) {
try {
return _fs.statSync(path).mtime;
}
catch (e) {
return undefined;
}
},
createHash(data) {
const hash = _crypto.createHash("md5");
hash.update(data);
return hash.digest("hex");
},
getMemoryUsage() {
if (global.gc) {
global.gc();
@ -626,7 +642,10 @@ namespace ts {
};
}
if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") {
return getWScriptSystem();
}
else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
@ -634,9 +653,6 @@ namespace ts {
// process.browser check excludes webpack and browserify
return getNodeSystem();
}
else if (typeof ChakraHost !== "undefined") {
return getChakraSystem();
}
else {
return undefined; // Unsupported host
}

View File

@ -14,6 +14,20 @@ namespace ts {
}
}
function reportEmittedFiles(files: string[], host: CompilerHost): void {
if (!files || files.length == 0) {
return;
}
const currentDir = sys.getCurrentDirectory();
for (const file of files) {
const filepath = getNormalizedAbsolutePath(file, currentDir);
sys.write(`TSFILE: ${filepath}${sys.newLine}`);
}
}
/**
* Checks to see if the locale is in the appropriate format,
* and if it is, attempts to set the appropriate language.
@ -108,7 +122,6 @@ namespace ts {
sys.write(output);
}
const redForegroundEscapeSequence = "\u001b[91m";
const yellowForegroundEscapeSequence = "\u001b[93m";
const blueForegroundEscapeSequence = "\u001b[93m";
@ -240,11 +253,6 @@ namespace ts {
return typeof JSON === "object" && typeof JSON.parse === "function";
}
function isWatchSet(options: CompilerOptions) {
// Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}
export function executeCommandLine(args: string[]): void {
const commandLine = parseCommandLine(args);
let configFileName: string; // Configuration file name (if any)
@ -338,8 +346,7 @@ namespace ts {
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
}
if (configFileName) {
const configFilePath = toPath(configFileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
configFileWatcher = sys.watchFile(configFilePath, configFileChanged);
configFileWatcher = sys.watchFile(configFileName, configFileChanged);
}
if (sys.watchDirectory && configFileName) {
const directory = ts.getDirectoryPath(configFileName);
@ -451,8 +458,7 @@ namespace ts {
const sourceFile = hostGetSourceFile(fileName, languageVersion, onError);
if (sourceFile && isWatchSet(compilerOptions) && sys.watchFile) {
// Attach a file watcher
const filePath = toPath(sourceFile.fileName, sys.getCurrentDirectory(), createGetCanonicalFileName(sys.useCaseSensitiveFileNames));
sourceFile.fileWatcher = sys.watchFile(filePath, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
sourceFile.fileWatcher = sys.watchFile(sourceFile.fileName, (fileName: string, removed?: boolean) => sourceFileChanged(sourceFile, removed));
}
return sourceFile;
}
@ -604,6 +610,8 @@ namespace ts {
reportDiagnostics(sortAndDeduplicateDiagnostics(diagnostics), compilerHost);
reportEmittedFiles(emitOutput.emittedFiles, compilerHost);
if (emitOutput.emitSkipped && diagnostics.length > 0) {
// If the emitter didn't emit anything, then pass that value along.
return ExitStatus.DiagnosticsPresent_OutputsSkipped;
@ -655,6 +663,8 @@ namespace ts {
const usageColumn: string[] = []; // Things like "-d, --declaration" go in here.
const descriptionColumn: string[] = [];
const optionsDescriptionMap: Map<string[]> = {}; // Map between option.description and list of option.type if it is a kind
for (let i = 0; i < optsList.length; i++) {
const option = optsList[i];
@ -675,7 +685,22 @@ namespace ts {
usageText += getParamType(option);
usageColumn.push(usageText);
descriptionColumn.push(getDiagnosticText(option.description));
let description: string;
if (option.name === "lib") {
description = getDiagnosticText(option.description);
const options: string[] = [];
const element = (<CommandLineOptionOfListType>option).element;
forEachKey(<Map<number | string>>element.type, key => {
options.push(`'${key}'`);
});
optionsDescriptionMap[description] = options;
}
else {
description = getDiagnosticText(option.description);
}
descriptionColumn.push(description);
// Set the new margin for the description column if necessary.
marginLength = Math.max(usageText.length, marginLength);
@ -691,7 +716,16 @@ namespace ts {
for (let i = 0; i < usageColumn.length; i++) {
const usage = usageColumn[i];
const description = descriptionColumn[i];
const kindsList = optionsDescriptionMap[description];
output += usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine;
if (kindsList) {
output += makePadding(marginLength + 4);
for (const kind of kindsList) {
output += kind + " ";
}
output += sys.newLine;
}
}
sys.write(output);

View File

@ -410,6 +410,7 @@ namespace ts {
JavaScriptFile = 1 << 27, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 28, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 29, // If we've computed data from children and cached it in this node
HasJsxSpreadAttribute = 1 << 30,
Modifier = Export | Ambient | Public | Private | Protected | Static | Abstract | Default | Async,
AccessibilityModifier = Public | Private | Protected,
@ -1566,6 +1567,7 @@ namespace ts {
amdDependencies: AmdDependency[];
moduleName: string;
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
languageVariant: LanguageVariant;
isDeclarationFile: boolean;
@ -1613,6 +1615,7 @@ namespace ts {
// It is used to resolve module names in the checker.
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<ResolvedModule>;
/* @internal */ resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
}
@ -1689,6 +1692,7 @@ namespace ts {
/* @internal */ getTypeCount(): number;
/* @internal */ getFileProcessingDiagnostics(): DiagnosticCollection;
/* @internal */ getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
// For testing purposes only.
/* @internal */ structureIsReused?: boolean;
}
@ -1739,6 +1743,7 @@ namespace ts {
emitSkipped: boolean;
/** Contains declaration emit diagnostics */
diagnostics: Diagnostic[];
emittedFiles: string[]; // Array of files the compiler wrote to disk
/* @internal */ sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
}
@ -1748,6 +1753,7 @@ namespace ts {
getSourceFiles(): SourceFile[];
getSourceFile(fileName: string): SourceFile;
getResolvedTypeReferenceDirectives(): Map<ResolvedTypeReferenceDirective>;
}
export interface TypeChecker {
@ -1765,6 +1771,7 @@ namespace ts {
getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[];
getShorthandAssignmentValueSymbol(location: Node): Symbol;
getExportSpecifierLocalTargetSymbol(location: ExportSpecifier): Symbol;
getPropertySymbolOfDestructuringAssignment(location: Identifier): Symbol;
getTypeAtLocation(node: Node): Type;
typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string;
symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string;
@ -1808,7 +1815,7 @@ namespace ts {
buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForParametersAndDelimiters(thisType: Type, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void;
}
@ -1955,6 +1962,8 @@ namespace ts {
moduleExportsSomeValue(moduleReferenceExpression: Expression): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile;
getTypeReferenceDirectivesForEntityName(name: EntityName | PropertyAccessExpression): string[];
getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[];
}
export const enum SymbolFlags {
@ -2310,6 +2319,7 @@ namespace ts {
declaration: SignatureDeclaration; // Originating declaration
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
parameters: Symbol[]; // Parameters
thisType?: Type; // type of this-type
/* @internal */
resolvedReturnType: Type; // Resolved return type
/* @internal */
@ -2445,6 +2455,7 @@ namespace ts {
jsx?: JsxEmit;
reactNamespace?: string;
listFiles?: boolean;
typesSearchPaths?: string[];
locale?: string;
mapRoot?: string;
module?: ModuleKind;
@ -2454,6 +2465,7 @@ namespace ts {
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noLib?: boolean;
noResolve?: boolean;
out?: string;
@ -2483,11 +2495,12 @@ namespace ts {
baseUrl?: string;
paths?: PathSubstitutions;
rootDirs?: RootPaths;
traceModuleResolution?: boolean;
traceResolution?: boolean;
allowSyntheticDefaultImports?: boolean;
allowJs?: boolean;
noImplicitUseStrict?: boolean;
strictNullChecks?: boolean;
listEmittedFiles?: boolean;
lib?: string[];
/* @internal */ stripInternal?: boolean;
@ -2496,8 +2509,15 @@ namespace ts {
// Do not perform validation of output file name in transpile scenarios
/* @internal */ suppressOutputPathCheck?: boolean;
list?: string[];
/* @internal */
// When options come from a config file, its path is recorded here
configFilePath?: string;
/* @internal */
// Path used to used to compute primary search locations
typesRoot?: string;
types?: string[];
list?: string[];
[option: string]: CompilerOptionsValue;
}
@ -2778,10 +2798,23 @@ namespace ts {
failedLookupLocations: string[];
}
export interface ResolvedTypeReferenceDirective {
// True if the type declaration file was found in a primary lookup location
primary: boolean;
// The location of the .d.ts file we located, or undefined if resolution failed
resolvedFileName?: string;
}
export interface ResolvedTypeReferenceDirectiveWithFailedLookupLocations {
resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective;
failedLookupLocations: string[];
}
export interface CompilerHost extends ModuleResolutionHost {
getSourceFile(fileName: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile;
getCancellationToken?(): CancellationToken;
getDefaultLibFileName(options: CompilerOptions): string;
getDefaultLibLocation?(): string;
writeFile: WriteFileCallback;
getCurrentDirectory(): string;
getCanonicalFileName(fileName: string): string;
@ -2796,6 +2829,10 @@ namespace ts {
* 'throw new Error("NotImplemented")'
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
/**
* 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[];
}
export interface TextSpan {

View File

@ -6,6 +6,7 @@ namespace ts {
fileReference?: FileReference;
diagnosticMessage?: DiagnosticMessage;
isNoDefaultLib?: boolean;
isTypeReferenceDirective?: boolean;
}
export interface SynthesizedNode extends Node {
@ -118,6 +119,43 @@ namespace ts {
sourceFile.resolvedModules[moduleNameText] = resolvedModule;
}
export function setResolvedTypeReferenceDirective(sourceFile: SourceFile, typeReferenceDirectiveName: string, resolvedTypeReferenceDirective: ResolvedTypeReferenceDirective): void {
if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
sourceFile.resolvedTypeReferenceDirectiveNames = {};
}
sourceFile.resolvedTypeReferenceDirectiveNames[typeReferenceDirectiveName] = resolvedTypeReferenceDirective;
}
/* @internal */
export function moduleResolutionIsEqualTo(oldResolution: ResolvedModule, newResolution: ResolvedModule): boolean {
return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport;
}
/* @internal */
export function typeDirectiveIsEqualTo(oldResolution: ResolvedTypeReferenceDirective, newResolution: ResolvedTypeReferenceDirective): boolean {
return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
}
/* @internal */
export function hasChangesInResolutions<T>(names: string[], newResolutions: T[], oldResolutions: Map<T>, comparer: (oldResolution: T, newResolution: T) => boolean): boolean {
if (names.length !== newResolutions.length) {
return false;
}
for (let i = 0; i < names.length; i++) {
const newResolution = newResolutions[i];
const oldResolution = oldResolutions && hasProperty(oldResolutions, names[i]) ? oldResolutions[names[i]] : undefined;
const changed =
oldResolution
? !newResolution || !comparer(oldResolution, newResolution)
: newResolution;
if (changed) {
return true;
}
}
return false;
}
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
@ -179,6 +217,33 @@ namespace ts {
return node.pos;
}
export function getEndLinePosition(line: number, sourceFile: SourceFile): number {
Debug.assert(line >= 0);
const lineStarts = getLineStarts(sourceFile);
const lineIndex = line;
const sourceText = sourceFile.text;
if (lineIndex + 1 === lineStarts.length) {
// last line - return EOF
return sourceText.length - 1;
}
else {
// current line start
const start = lineStarts[lineIndex];
// take the start position of the next line - 1 = it should be some line break
let pos = lineStarts[lineIndex + 1] - 1;
Debug.assert(isLineBreak(sourceText.charCodeAt(pos)));
// walk backwards skipping line breaks, stop the the beginning of current line.
// i.e:
// <some text>
// $ <- end of line for this position should match the start position
while (start <= pos && isLineBreak(sourceText.charCodeAt(pos))) {
pos--;
}
return pos;
}
}
// 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
@ -402,6 +467,20 @@ namespace ts {
return createTextSpanFromBounds(start, scanner.getTextPos());
}
function getErrorSpanForArrowFunction(sourceFile: SourceFile, node: ArrowFunction): TextSpan {
const pos = skipTrivia(sourceFile.text, node.pos);
if (node.body && node.body.kind === SyntaxKind.Block) {
const { line: startLine } = getLineAndCharacterOfPosition(sourceFile, node.body.pos);
const { line: endLine } = getLineAndCharacterOfPosition(sourceFile, node.body.end);
if (startLine < endLine) {
// The arrow function spans multiple lines,
// make the error span be the first line, inclusive.
return createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
}
}
return createTextSpanFromBounds(pos, node.end);
}
export function getErrorSpanForNode(sourceFile: SourceFile, node: Node): TextSpan {
let errorNode = node;
switch (node.kind) {
@ -430,6 +509,8 @@ namespace ts {
case SyntaxKind.TypeAliasDeclaration:
errorNode = (<Declaration>node).name;
break;
case SyntaxKind.ArrowFunction:
return getErrorSpanForArrowFunction(sourceFile, <ArrowFunction>node);
}
if (errorNode === undefined) {
@ -536,6 +617,7 @@ namespace ts {
}
export let fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export let fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
export let fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
export function isTypeNode(node: Node): boolean {
@ -1591,25 +1673,26 @@ namespace ts {
};
}
else {
const matchResult = fullTripleSlashReferencePathRegEx.exec(comment);
if (matchResult) {
const refMatchResult = fullTripleSlashReferencePathRegEx.exec(comment);
const refLibResult = !refMatchResult && fullTripleSlashReferenceTypeReferenceDirectiveRegEx.exec(comment);
if (refMatchResult || refLibResult) {
const start = commentRange.pos;
const end = commentRange.end;
return {
fileReference: {
pos: start,
end: end,
fileName: matchResult[3]
fileName: (refMatchResult || refLibResult)[3]
},
isNoDefaultLib: false
};
}
else {
return {
diagnosticMessage: Diagnostics.Invalid_reference_directive_syntax,
isNoDefaultLib: false
isNoDefaultLib: false,
isTypeReferenceDirective: !!refLibResult
};
}
return {
diagnosticMessage: Diagnostics.Invalid_reference_directive_syntax,
isNoDefaultLib: false
};
}
}
@ -2685,6 +2768,11 @@ namespace ts {
}
return carriageReturnLineFeed;
}
export function isWatchSet(options: CompilerOptions) {
// Firefox has Object.prototype.watch
return options.watch && options.hasOwnProperty("watch");
}
}
namespace ts {
@ -2922,4 +3010,13 @@ namespace ts {
export function isParameterPropertyDeclaration(node: ParameterDeclaration): boolean {
return node.flags & NodeFlags.AccessibilityModifier && node.parent.kind === SyntaxKind.Constructor && isClassLike(node.parent.parent);
}
export function startsWith(str: string, prefix: string): boolean {
return str.lastIndexOf(prefix, 0) === 0;
}
export function endsWith(str: string, suffix: string): boolean {
const expectedPos = str.length - suffix.length;
return str.indexOf(suffix, expectedPos) === expectedPos;
}
}

View File

@ -1,7 +1,7 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/// <reference path="typeWriter.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
const enum CompilerTestType {
Conformance,
@ -102,6 +102,10 @@ class CompilerBaselineRunner extends RunnerBase {
});
}
if (tsConfigOptions && tsConfigOptions.configFilePath !== undefined) {
tsConfigOptions.configFilePath = ts.combinePaths(rootDir, tsConfigOptions.configFilePath);
}
const output = Harness.Compiler.compileFiles(
toBeCompiled, otherFiles, harnessSettings, /*options*/ tsConfigOptions, /*currentDirectory*/ undefined);
@ -140,7 +144,7 @@ class CompilerBaselineRunner extends RunnerBase {
});
it (`Correct module resolution tracing for ${fileName}`, () => {
if (options.traceModuleResolution) {
if (options.traceResolution) {
Harness.Baseline.runBaseline("Correct sourcemap content for " + fileName, justName.replace(/\.tsx?$/, ".trace.json"), () => {
return JSON.stringify(result.traceResults || [], undefined, 4);
});
@ -252,125 +256,128 @@ class CompilerBaselineRunner extends RunnerBase {
}
// NEWTODO: Type baselines
if (result.errors.length === 0) {
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type displayed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
}
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
}
if (e1 || e2) {
throw e1 || e2;
}
if (result.errors.length !== 0) {
return;
}
function checkBaseLines(isSymbolBaseLine: boolean) {
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
// The full walker simulates the types that you would get from doing a full
// compile. The pull walker simulates the types you get when you just do
// a type query for a random node (like how the LS would do it). Most of the
// time, these will be the same. However, occasionally, they can be different.
// Specifically, when the compiler internally depends on symbol IDs to order
// things, then we may see different results because symbols can be created in a
// different order with 'pull' operations, and thus can produce slightly differing
// output.
//
// For example, with a full type check, we may see a type displayed as: number | string
// But with a pull type check, we may see it as: string | number
//
// These types are equivalent, but depend on what order the compiler observed
// certain parts of the program.
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
const program = result.program;
const allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
const fullWalker = new TypeWriterWalker(program, /*fullTypeCheck*/ true);
const fullResults: ts.Map<TypeWriterResult[]> = {};
const pullResults: ts.Map<TypeWriterResult[]> = {};
for (const sourceFile of allFiles) {
fullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
pullResults[sourceFile.unitName] = fullWalker.getTypeAndSymbols(sourceFile.unitName);
}
// Produce baselines. The first gives the types for all expressions.
// The second gives symbols for all identifiers.
let e1: Error, e2: Error;
try {
checkBaseLines(/*isSymbolBaseLine*/ false);
}
catch (e) {
e1 = e;
}
try {
checkBaseLines(/*isSymbolBaseLine*/ true);
}
catch (e) {
e2 = e;
}
if (e1 || e2) {
throw e1 || e2;
}
return;
function checkBaseLines(isSymbolBaseLine: boolean) {
const fullBaseLine = generateBaseLine(fullResults, isSymbolBaseLine);
const pullBaseLine = generateBaseLine(pullResults, isSymbolBaseLine);
const fullExtension = isSymbolBaseLine ? ".symbols" : ".types";
const pullExtension = isSymbolBaseLine ? ".symbols.pull" : ".types.pull";
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline("Correct full information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline("Correct pull information for " + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
const codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
let typeInfo = [formattedLine];
const existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
const currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
const typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push("\r\n");
}
}
}
else {
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join("");
else {
Harness.Baseline.runBaseline("Correct information for " + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
function generateBaseLine(typeWriterResults: ts.Map<TypeWriterResult[]>, isSymbolBaseline: boolean): string {
const typeLines: string[] = [];
const typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
allFiles.forEach(file => {
const codeLines = file.content.split("\n");
typeWriterResults[file.unitName].forEach(result => {
if (isSymbolBaseline && !result.symbol) {
return;
}
const typeOrSymbolString = isSymbolBaseline ? result.symbol : result.type;
const formattedLine = result.sourceText.replace(/\r?\n/g, "") + " : " + typeOrSymbolString;
if (!typeMap[file.unitName]) {
typeMap[file.unitName] = {};
}
let typeInfo = [formattedLine];
const existingTypeInfo = typeMap[file.unitName][result.line];
if (existingTypeInfo) {
typeInfo = existingTypeInfo.concat(typeInfo);
}
typeMap[file.unitName][result.line] = typeInfo;
});
typeLines.push("=== " + file.unitName + " ===\r\n");
for (let i = 0; i < codeLines.length; i++) {
const currentCodeLine = codeLines[i];
typeLines.push(currentCodeLine + "\r\n");
if (typeMap[file.unitName]) {
const typeInfo = typeMap[file.unitName][i];
if (typeInfo) {
typeInfo.forEach(ty => {
typeLines.push(">" + ty + "\r\n");
});
if (i + 1 < codeLines.length && (codeLines[i + 1].match(/^\s*[{|}]\s*$/) || codeLines[i + 1].trim() === "")) {
}
else {
typeLines.push("\r\n");
}
}
}
else {
typeLines.push("No type information for this code.");
}
}
});
return typeLines.join("");
}
});
});
}

View File

@ -18,7 +18,7 @@
/// <reference path="harnessLanguageService.ts" />
/// <reference path="harness.ts" />
/// <reference path="fourslashRunner.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace FourSlash {
ts.disableIncrementalParsing = false;
@ -221,8 +221,8 @@ namespace FourSlash {
function tryAdd(path: string) {
const inputFile = inputFiles[path];
if (inputFile && !Harness.isLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile);
if (inputFile && !Harness.isDefaultLibraryFile(path)) {
languageServiceAdapterHost.addScript(path, inputFile, /*isRootFile*/ true);
return true;
}
}
@ -247,6 +247,10 @@ namespace FourSlash {
// Create a new Services Adapter
this.cancellationToken = new TestCancellationToken();
const compilationOptions = convertGlobalOptionsToCompilerOptions(this.testData.globalOptions);
if (compilationOptions.typesRoot) {
compilationOptions.typesRoot = ts.getNormalizedAbsolutePath(compilationOptions.typesRoot, this.basePath);
}
const languageServiceAdapter = this.getLanguageServiceAdapter(testType, this.cancellationToken, compilationOptions);
this.languageServiceAdapterHost = languageServiceAdapter.getHost();
this.languageService = languageServiceAdapter.getLanguageService();
@ -268,7 +272,7 @@ namespace FourSlash {
if (startResolveFileRef) {
// Add the entry-point file itself into the languageServiceShimHost
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content);
this.languageServiceAdapterHost.addScript(startResolveFileRef.fileName, startResolveFileRef.content, /*isRootFile*/ true);
const resolvedResult = languageServiceAdapter.getPreProcessedFileInfo(startResolveFileRef.fileName, startResolveFileRef.content);
const referencedFiles: ts.FileReference[] = resolvedResult.referencedFiles;
@ -291,17 +295,19 @@ namespace FourSlash {
// Check if no-default-lib flag is false and if so add default library
if (!resolvedResult.isLibFile) {
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
}
else {
// resolveReference file-option is not specified then do not resolve any files and include all inputFiles
ts.forEachKey(this.inputFiles, fileName => {
if (!Harness.isLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName]);
if (!Harness.isDefaultLibraryFile(fileName)) {
this.languageServiceAdapterHost.addScript(fileName, this.inputFiles[fileName], /*isRootFile*/ true);
}
});
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName, Harness.Compiler.defaultLibSourceFile.text);
this.languageServiceAdapterHost.addScript(Harness.Compiler.defaultLibFileName,
Harness.Compiler.getDefaultLibrarySourceFile().text, /*isRootFile*/ false);
}
this.formatCodeOptions = {

View File

@ -1,7 +1,7 @@
///<reference path="fourslash.ts" />
///<reference path="harness.ts"/>
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
const enum FourSlashTestType {
Native,

View File

@ -23,7 +23,7 @@
/// <reference path="external\chai.d.ts"/>
/// <reference path="sourceMapRecorder.ts"/>
/// <reference path="runnerbase.ts"/>
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
// Block scoped definitions work poorly for global variables, temporarily enable var
/* tslint:disable:no-var-keyword */
@ -65,6 +65,11 @@ namespace Utils {
return Buffer ? (new Buffer(s)).toString("utf8") : s;
}
export function byteLength(s: string, encoding?: string): number {
// stub implementation if Buffer is not available (in-browser case)
return Buffer ? Buffer.byteLength(s, encoding) : s.length;
}
export function evalFile(fileContents: string, fileName: string, nodeContext?: any) {
const environment = getExecutionEnvironment();
switch (environment) {
@ -817,15 +822,33 @@ namespace Harness {
const lineFeed = "\n";
export const defaultLibFileName = "lib.d.ts";
export const defaultLibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const defaultES6LibSourceFile = createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.core.es6.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest);
export const es2015DefaultLibFileName = "lib.es2015.d.ts";
const libFileNameSourceFileMap: ts.Map<ts.SourceFile> = {
[defaultLibFileName]: createSourceFileAndAssertInvariants(defaultLibFileName, IO.readFile(libFolder + "lib.es5.d.ts"), /*languageVersion*/ ts.ScriptTarget.Latest)
};
export function getDefaultLibrarySourceFile(fileName = defaultLibFileName): ts.SourceFile {
if (!isDefaultLibraryFile(fileName)) {
return undefined;
}
if (!libFileNameSourceFileMap[fileName]) {
libFileNameSourceFileMap[fileName] = createSourceFileAndAssertInvariants(fileName, IO.readFile(libFolder + fileName), ts.ScriptTarget.Latest);
}
return libFileNameSourceFileMap[fileName];
}
export function getDefaultLibFileName(options: ts.CompilerOptions): string {
return options.target === ts.ScriptTarget.ES6 ? es2015DefaultLibFileName : defaultLibFileName;
}
// Cache these between executions so we don't have to re-parse them for every test
export const fourslashFileName = "fourslash.ts";
export let fourslashSourceFile: ts.SourceFile;
export function getCanonicalFileName(fileName: string): string {
return Harness.IO.useCaseSensitiveFileNames() ? fileName : fileName.toLowerCase();
return fileName;
}
export function createCompilerHost(
@ -850,23 +873,21 @@ namespace Harness {
}
}
function getSourceFile(fn: string, languageVersion: ts.ScriptTarget) {
fn = ts.normalizePath(fn);
const path = ts.toPath(fn, currentDirectory, getCanonicalFileName);
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget) {
fileName = ts.normalizePath(fileName);
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
return fileMap.get(path);
}
else if (fn === fourslashFileName) {
else if (fileName === fourslashFileName) {
const tsFn = "tests/cases/fourslash/" + fourslashFileName;
fourslashSourceFile = fourslashSourceFile || createSourceFileAndAssertInvariants(tsFn, Harness.IO.readFile(tsFn), scriptTarget);
return fourslashSourceFile;
}
else {
if (fn === defaultLibFileName) {
return languageVersion === ts.ScriptTarget.ES6 ? defaultES6LibSourceFile : defaultLibSourceFile;
}
// Don't throw here -- the compiler might be looking for a test that actually doesn't exist as part of the TC
return undefined;
// Return if it is other library file, otherwise return undefined
return getDefaultLibrarySourceFile(fileName);
}
}
@ -875,16 +896,21 @@ namespace Harness {
newLineKind === ts.NewLineKind.LineFeed ? lineFeed :
Harness.IO.newLine();
return {
getCurrentDirectory: () => currentDirectory,
getSourceFile,
getDefaultLibFileName: options => defaultLibFileName,
getDefaultLibFileName,
writeFile,
getCanonicalFileName,
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => newLine,
fileExists: fileName => getSourceFile(fileName, ts.ScriptTarget.ES5) !== undefined,
readFile: (fileName: string): string => { return Harness.IO.readFile(fileName); }
fileExists: fileName => {
return fileMap.contains(ts.toPath(fileName, currentDirectory, getCanonicalFileName));
},
readFile: (fileName: string): string => {
return fileMap.get(ts.toPath(fileName, currentDirectory, getCanonicalFileName)).getText();
}
};
}
@ -929,6 +955,7 @@ namespace Harness {
}
const option = getCommandLineOption(name);
if (option) {
const errors: ts.Diagnostic[] = [];
switch (option.type) {
case "boolean":
options[option.name] = value.toLowerCase() === "true";
@ -937,15 +964,16 @@ namespace Harness {
options[option.name] = value;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
case "list":
options[option.name] = ts.parseListTypeOption(<ts.CommandLineOptionOfListType>option, value, errors);
break;
default:
let map = <ts.Map<number>>option.type;
let key = value.toLowerCase();
if (ts.hasProperty(map, key)) {
options[option.name] = map[key];
}
else {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
options[option.name] = ts.parseCustomTypeOption(<ts.CommandLineOptionOfCustomType>option, value, errors);
break;
}
if (errors.length > 0) {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
}
else {
@ -972,7 +1000,6 @@ namespace Harness {
compilerOptions: ts.CompilerOptions,
// Current directory is needed for rwcRunner to be able to use currentDirectory defined in json file
currentDirectory: string): CompilationOutput {
const options: ts.CompilerOptions & HarnessOptions = compilerOptions ? ts.clone(compilerOptions) : { noResolve: false };
options.target = options.target || ts.ScriptTarget.ES3;
options.newLine = options.newLine || ts.NewLineKind.CarriageReturnLineFeed;
@ -1024,7 +1051,7 @@ namespace Harness {
options.newLine);
let traceResults: string[];
if (options.traceModuleResolution) {
if (options.traceResolution) {
traceResults = [];
compilerHost.trace = text => traceResults.push(text);
}
@ -1147,7 +1174,7 @@ namespace Harness {
// then they will be added twice thus triggering 'total errors' assertion with condition
// 'totalErrorsReportedInNonLibraryFiles + numLibraryDiagnostics + numTest262HarnessDiagnostics, diagnostics.length
if (!error.file || !isLibraryFile(error.file.fileName)) {
if (!error.file || !isDefaultLibraryFile(error.file.fileName)) {
totalErrorsReportedInNonLibraryFiles++;
}
}
@ -1226,7 +1253,7 @@ namespace Harness {
});
const numLibraryDiagnostics = ts.countWhere(diagnostics, diagnostic => {
return diagnostic.file && (isLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
return diagnostic.file && (isDefaultLibraryFile(diagnostic.file.fileName) || isBuiltFile(diagnostic.file.fileName));
});
const numTest262HarnessDiagnostics = ts.countWhere(diagnostics, diagnostic => {
@ -1470,6 +1497,7 @@ namespace Harness {
baseDir = ts.getNormalizedAbsolutePath(baseDir, rootDir);
}
tsConfig = ts.parseJsonConfigFileContent(configJson.config, parseConfigHost, baseDir);
tsConfig.options.configFilePath = data.name;
// delete entry from the list
testUnitData.splice(i, 1);
@ -1613,8 +1641,10 @@ namespace Harness {
}
}
export function isLibraryFile(filePath: string): boolean {
return (Path.getFileName(filePath) === "lib.d.ts") || (Path.getFileName(filePath) === "lib.core.d.ts");
export function isDefaultLibraryFile(filePath: string): boolean {
// We need to make sure that the filePath is prefixed with "lib." not just containing "lib." and end with ".d.ts"
const fileName = Path.getFileName(filePath);
return ts.startsWith(fileName, "lib.") && ts.endsWith(fileName, ".d.ts");
}
export function isBuiltFile(filePath: string): boolean {
@ -1622,7 +1652,7 @@ namespace Harness {
}
export function getDefaultLibraryFile(io: Harness.IO): Harness.Compiler.TestFile {
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + "lib.d.ts";
const libFile = Harness.userSpecifiedRoot + Harness.libFolder + Harness.Compiler.defaultLibFileName;
return { unitName: libFile, content: io.readFile(libFile) };
}

View File

@ -9,7 +9,7 @@ namespace Harness.LanguageService {
public editRanges: { length: number; textChangeRange: ts.TextChangeRange; }[] = [];
private lineMap: number[] = undefined;
constructor(public fileName: string, public content: string) {
constructor(public fileName: string, public content: string, public isRootFile: boolean) {
this.setContent(content);
}
@ -135,7 +135,13 @@ namespace Harness.LanguageService {
public getFilenames(): string[] {
const fileNames: string[] = [];
ts.forEachKey(this.fileNameToScript, (fileName) => { fileNames.push(fileName); });
ts.forEachValue(this.fileNameToScript, (scriptInfo) => {
if (scriptInfo.isRootFile) {
// only include root files here
// usually it means that we won't include lib.d.ts in the list of root files so it won't mess the computation of compilation root dir.
fileNames.push(scriptInfo.fileName);
}
});
return fileNames;
}
@ -143,8 +149,8 @@ namespace Harness.LanguageService {
return ts.lookUp(this.fileNameToScript, fileName);
}
public addScript(fileName: string, content: string): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content);
public addScript(fileName: string, content: string, isRootFile: boolean): void {
this.fileNameToScript[fileName] = new ScriptInfo(fileName, content, isRootFile);
}
public editScript(fileName: string, start: number, end: number, newText: string) {
@ -177,7 +183,7 @@ namespace Harness.LanguageService {
getCompilationSettings() { return this.settings; }
getCancellationToken() { return this.cancellationToken; }
getCurrentDirectory(): string { return ""; }
getDefaultLibFileName(): string { return ""; }
getDefaultLibFileName(): string { return Harness.Compiler.defaultLibFileName; }
getScriptFileNames(): string[] { return this.getFilenames(); }
getScriptSnapshot(fileName: string): ts.IScriptSnapshot {
const script = this.getScriptInfo(fileName);
@ -210,6 +216,7 @@ namespace Harness.LanguageService {
private nativeHost: NativeLanguageServiceHost;
public getModuleResolutionsForFile: (fileName: string) => string;
public getTypeReferenceDirectiveResolutionsForFile: (fileName: string) => string;
constructor(preprocessToResolve: boolean, cancellationToken?: ts.HostCancellationToken, options?: ts.CompilerOptions) {
super(cancellationToken, options);
@ -236,12 +243,25 @@ namespace Harness.LanguageService {
}
return JSON.stringify(imports);
};
this.getTypeReferenceDirectiveResolutionsForFile = (fileName) => {
const scriptInfo = this.getScriptInfo(fileName);
const preprocessInfo = ts.preProcessFile(scriptInfo.content, /*readImportFiles*/ false);
const resolutions: ts.Map<ts.ResolvedTypeReferenceDirective> = {};
const settings = this.nativeHost.getCompilationSettings();
for (const typeReferenceDirective of preprocessInfo.typeReferenceDirectives) {
const resolutionInfo = ts.resolveTypeReferenceDirective(typeReferenceDirective.fileName, fileName, settings, moduleResolutionHost);
if (resolutionInfo.resolvedTypeReferenceDirective.resolvedFileName) {
resolutions[typeReferenceDirective.fileName] = resolutionInfo.resolvedTypeReferenceDirective;
}
}
return JSON.stringify(resolutions);
};
}
}
getFilenames(): string[] { return this.nativeHost.getFilenames(); }
getScriptInfo(fileName: string): ScriptInfo { return this.nativeHost.getScriptInfo(fileName); }
addScript(fileName: string, content: string): void { this.nativeHost.addScript(fileName, content); }
addScript(fileName: string, content: string, isRootFile: boolean): void { this.nativeHost.addScript(fileName, content, isRootFile); }
editScript(fileName: string, start: number, end: number, newText: string): void { this.nativeHost.editScript(fileName, start, end, newText); }
positionToLineAndCharacter(fileName: string, position: number): ts.LineAndCharacter { return this.nativeHost.positionToLineAndCharacter(fileName, position); }
@ -442,6 +462,7 @@ namespace Harness.LanguageService {
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo {
let shimResult: {
referencedFiles: ts.IFileReference[];
typeReferenceDirectives: ts.IFileReference[];
importedFiles: ts.IFileReference[];
isLibFile: boolean;
};
@ -453,7 +474,8 @@ namespace Harness.LanguageService {
referencedFiles: [],
importedFiles: [],
ambientExternalModules: [],
isLibFile: shimResult.isLibFile
isLibFile: shimResult.isLibFile,
typeReferenceDirectives: []
};
ts.forEach(shimResult.referencedFiles, refFile => {
@ -472,6 +494,13 @@ namespace Harness.LanguageService {
});
});
ts.forEach(shimResult.typeReferenceDirectives, typeRefDirective => {
convertResult.importedFiles.push({
fileName: typeRefDirective.path,
pos: typeRefDirective.position,
end: typeRefDirective.position + typeRefDirective.length
});
});
return convertResult;
}
}

View File

@ -1,7 +1,7 @@
/// <reference path="..\..\src\compiler\sys.ts" />
/// <reference path="..\..\src\harness\harness.ts" />
/// <reference path="..\..\src\harness\runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
interface FileInformation {
contents: string;
@ -237,8 +237,8 @@ namespace Playback {
), path));
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path, contents) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path, contents) => noOpReplay("writeFile"));
(path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path: string, contents: string) => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {

View File

@ -1,6 +1,6 @@
///<reference path="harness.ts" />
///<reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
// Test case is json of below type in tests/cases/project/
interface ProjectRunnerTestCase {
@ -156,7 +156,7 @@ class ProjectRunner extends RunnerBase {
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile {
let sourceFile: ts.SourceFile = undefined;
if (fileName === Harness.Compiler.defaultLibFileName) {
sourceFile = languageVersion === ts.ScriptTarget.ES6 ? Harness.Compiler.defaultES6LibSourceFile : Harness.Compiler.defaultLibSourceFile;
sourceFile = Harness.Compiler.getDefaultLibrarySourceFile(Harness.Compiler.getDefaultLibFileName(compilerOptions));
}
else {
const text = getSourceFileText(fileName);
@ -412,7 +412,7 @@ class ProjectRunner extends RunnerBase {
function getErrorsBaseline(compilerResult: CompileProjectFilesResult) {
const inputFiles = compilerResult.program ? ts.map(ts.filter(compilerResult.program.getSourceFiles(),
sourceFile => sourceFile.fileName !== "lib.d.ts"),
sourceFile => !Harness.isDefaultLibraryFile(sourceFile.fileName)),
sourceFile => {
return {
unitName: ts.isRootedDiskPath(sourceFile.fileName) ?

View File

@ -20,7 +20,7 @@
/// <reference path="rwcRunner.ts" />
/// <reference path="harness.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
let runners: RunnerBase[] = [];
let iterations = 1;

View File

@ -2,7 +2,7 @@
/// <reference path="runnerbase.ts" />
/// <reference path="loggedIO.ts" />
/// <reference path="..\compiler\commandLineParser.ts"/>
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace RWC {
function runWithIOLog(ioLog: IOLog, fn: (oldIO: Harness.IO) => void) {
@ -95,13 +95,13 @@ namespace RWC {
continue;
}
if (!Harness.isLibraryFile(fileRead.path)) {
if (!Harness.isDefaultLibraryFile(fileRead.path)) {
if (inInputList) {
continue;
}
otherFiles.push(getHarnessCompilerInputUnit(fileRead.path));
}
else if (!opts.options.noLib && Harness.isLibraryFile(fileRead.path)) {
else if (!opts.options.noLib && Harness.isDefaultLibraryFile(fileRead.path)) {
if (!inInputList) {
// If useCustomLibraryFile is true, we will use lib.d.ts from json object
// otherwise use the lib.d.ts from built/local

View File

@ -1,6 +1,6 @@
/// <reference path="harness.ts" />
/// <reference path="runnerbase.ts" />
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
class Test262BaselineRunner extends RunnerBase {
private static basePath = "internal/cases/test262";

File diff suppressed because it is too large Load Diff

View File

@ -1,3 +1,5 @@
/// <reference path="lib.dom.generated.d.ts" />
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}

70
src/lib/es2015.collection.d.ts vendored Normal file
View File

@ -0,0 +1,70 @@
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): Map<K, V>;
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface WeakMap<K, V> {
clear(): void;
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value?: V): WeakMap<K, V>;
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
add(value: T): Set<T>;
clear(): void;
delete(value: T): boolean;
entries(): IterableIterator<[T, T]>;
forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;
has(value: T): boolean;
keys(): IterableIterator<T>;
readonly size: number;
values(): IterableIterator<T>;
[Symbol.iterator]():IterableIterator<T>;
readonly [Symbol.toStringTag]: "Set";
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface WeakSet<T> {
add(value: T): WeakSet<T>;
clear(): void;
delete(value: T): boolean;
has(value: T): boolean;
readonly [Symbol.toStringTag]: "WeakSet";
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;

483
src/lib/es2015.core.d.ts vendored Normal file
View File

@ -0,0 +1,483 @@
declare type PropertyKey = string | number | symbol;
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T) => boolean, thisArg?: any): number | undefined;
/**
* Returns the this object after filling the section identified by start and end with value
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): T[];
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): T[];
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): Array<T>;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): Array<T>;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of
* the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[] ): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param s A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in numString.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface Object {
/**
* Determines whether an object has a property with the specified name.
* @param v A property name.
*/
hasOwnProperty(v: PropertyKey): boolean
/**
* Determines whether a specified property is enumerable.
* @param v A property name.
*/
propertyIsEnumerable(v: PropertyKey): boolean;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: any, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: any): any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not
* inherited from the object's prototype.
* @param o Object that contains the property.
* @param p Name of the property.
*/
getOwnPropertyDescriptor(o: any, propertyKey: PropertyKey): PropertyDescriptor;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param o Object on which to add or modify the property. This can be a native JavaScript
* object (that is, a user-defined object or a built in object) or a DOM object.
* @param p The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor
* property.
*/
defineProperty(o: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): any;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* T is the empty String is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an <a> HTML anchor element and sets the name attribute to the text value
* @param name
*/
anchor(name: string): string;
/** Returns a <big> HTML element */
big(): string;
/** Returns a <blink> HTML element */
blink(): string;
/** Returns a <b> HTML element */
bold(): string;
/** Returns a <tt> HTML element */
fixed(): string
/** Returns a <font> HTML element and sets the color attribute value */
fontcolor(color: string): string
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: number): string;
/** Returns a <font> HTML element and sets the size attribute value */
fontsize(size: string): string;
/** Returns an <i> HTML element */
italics(): string;
/** Returns an <a> HTML element and sets the href attribute value */
link(url: string): string;
/** Returns a <small> HTML element */
small(): string;
/** Returns a <strike> HTML element */
strike(): string;
/** Returns a <sub> HTML element */
sub(): string;
/** Returns a <sup> HTML element */
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is intended for use as a tag function of a Tagged Template String. When called
* as such the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}

10
src/lib/es2015.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
/// <reference path="lib.es2015.iterable.d.ts" />
/// <reference path="lib.es2015.promise.d.ts" />
/// <reference path="lib.es2015.proxy.d.ts" />
/// <reference path="lib.es2015.reflect.d.ts" />
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
/// <reference path="lib.es5.d.ts" />

12
src/lib/es2015.generator.d.ts vendored Normal file
View File

@ -0,0 +1,12 @@
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
(...args: string[]): GeneratorFunction;
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;

373
src/lib/es2015.iterable.d.ts vendored Normal file
View File

@ -0,0 +1,373 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface IteratorResult<T> {
done: boolean;
value?: T;
}
interface Iterator<T> {
next(value?: any): IteratorResult<T>;
return?(value?: any): IteratorResult<T>;
throw?(e?: any): IteratorResult<T>;
}
interface Iterable<T> { }
interface IterableIterator<T> extends Iterator<T> { }
interface Array<T> {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, T]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T>): Array<T>;
}
interface Map<K, V> {
entries(): IterableIterator<[K, V]>;
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
}
interface MapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
}
interface WeakMap<K, V> { }
interface WeakMapConstructor {
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
}
interface Promise<T> { }
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<TAll>(values: Iterable<TAll | PromiseLike<TAll>>): Promise<TAll[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<T>;
}
declare namespace Reflect {
function enumerate(target: any): IterableIterator<any>;
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int8Array;
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8Array;
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint8ClampedArray;
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int16Array;
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint16Array;
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Int32Array;
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Uint32Array;
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float32Array;
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): IterableIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): IterableIterator<number>;
/**
* Returns an list of values in the array
*/
values(): IterableIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like or iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}

81
src/lib/es2015.promise.d.ts vendored Normal file
View File

@ -0,0 +1,81 @@
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
catch(onrejected?: (reason: any) => void): Promise<T>;
}
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject(reason: any): Promise<void>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T>(reason: any): Promise<T>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<T>;
/**
* Creates a new resolved promise .
* @returns A resolved promise.
*/
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;

22
src/lib/es2015.proxy.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
preventExtensions? (target: T): boolean;
getOwnPropertyDescriptor? (target: T, p: PropertyKey): PropertyDescriptor;
has? (target: T, p: PropertyKey): boolean;
get? (target: T, p: PropertyKey, receiver: any): any;
set? (target: T, p: PropertyKey, value: any, receiver: any): boolean;
deleteProperty? (target: T, p: PropertyKey): boolean;
defineProperty? (target: T, p: PropertyKey, attributes: PropertyDescriptor): boolean;
enumerate? (target: T): PropertyKey[];
ownKeys? (target: T): PropertyKey[];
apply? (target: T, thisArg: any, argArray?: any): any;
construct? (target: T, thisArg: any, argArray?: any): any;
}
interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;

16
src/lib/es2015.reflect.d.ts vendored Normal file
View File

@ -0,0 +1,16 @@
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
function deleteProperty(target: any, propertyKey: PropertyKey): boolean;
function get(target: any, propertyKey: PropertyKey, receiver?: any): any;
function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;
function getPrototypeOf(target: any): any;
function has(target: any, propertyKey: string): boolean;
function has(target: any, propertyKey: symbol): boolean;
function isExtensible(target: any): boolean;
function ownKeys(target: any): Array<PropertyKey>;
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}

36
src/lib/es2015.symbol.d.ts vendored Normal file
View File

@ -0,0 +1,36 @@
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): Object;
}
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string|number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;

356
src/lib/es2015.symbol.wellknown.d.ts vendored Normal file
View File

@ -0,0 +1,356 @@
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: symbol;
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: symbol;
/**
* An Object whose own property names are property names that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: symbol;
}
interface Symbol {
readonly [Symbol.toStringTag]: "Symbol";
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): IterableIterator<T>;
/**
* Returns an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
[Symbol.unscopables](): {
copyWithin: boolean;
entries: boolean;
fill: boolean;
find: boolean;
findIndex: boolean;
keys: boolean;
values: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
[Symbol.iterator]():IterableIterator<[K,V]>;
readonly [Symbol.toStringTag]: "Map";
}
interface WeakMap<K, V>{
readonly [Symbol.toStringTag]: "WeakMap";
}
interface JSON {
readonly [Symbol.toStringTag]: "JSON";
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction extends Function {
readonly [Symbol.toStringTag]: "GeneratorFunction";
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): IterableIterator<any>;
}
interface Iterator<T> { }
interface Iterable<T> {
[Symbol.iterator](): Iterator<T>;
}
interface IterableIterator<T> extends Iterator<T> {
[Symbol.iterator](): IterableIterator<T>;
}
interface Math {
readonly [Symbol.toStringTag]: "Math";
}
interface Promise<T> {
readonly [Symbol.toStringTag]: "Promise";
}
interface PromiseConstructor {
readonly [Symbol.species]: Function;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
[Symbol.species](): RegExpConstructor;
}
interface String {
/** Iterator */
[Symbol.iterator](): IterableIterator<string>;
/**
* Matches a string an object that supports being matched against, and returns an array containing the results of that search.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
/**
* Represents a raw buffer of binary data, which is used to store data for the
* different typed arrays. ArrayBuffers cannot be read from or written to directly,
* but can be passed to a typed array or DataView Object to interpret the raw
* buffer as needed.
*/
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView {
readonly [Symbol.toStringTag]: "DataView";
}
/**
* A typed array of 8-bit integer values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Int8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int8Array";
}
/**
* A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "UInt8Array";
}
/**
* A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0.
* If the requested number of bytes could not be allocated an exception is raised.
*/
interface Uint8ClampedArray {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
/**
* A typed array of 16-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int16Array";
}
/**
* A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint16Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint16Array";
}
/**
* A typed array of 32-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Int32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Int32Array";
}
/**
* A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated an exception is raised.
*/
interface Uint32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Uint32Array";
}
/**
* A typed array of 32-bit float values. The contents are initialized to 0. If the requested number
* of bytes could not be allocated an exception is raised.
*/
interface Float32Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float32Array";
}
/**
* A typed array of 64-bit float values. The contents are initialized to 0. If the requested
* number of bytes could not be allocated an exception is raised.
*/
interface Float64Array {
[Symbol.iterator](): IterableIterator<number>;
readonly [Symbol.toStringTag]: "Float64Array";
}

2
src/lib/es2016.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />

View File

@ -215,14 +215,16 @@ interface Function {
* @param thisArg The object to be used as the this object.
* @param argArray A set of arguments to be passed to the function.
*/
apply(thisArg: any, argArray?: any): any;
apply<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U;
apply(this: Function, thisArg: any, argArray?: any): any;
/**
* Calls a method of an object, substituting another object for the current object.
* @param thisArg The object to be used as the current object.
* @param argArray A list of arguments to be passed to the method.
*/
call(thisArg: any, ...argArray: any[]): any;
call<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): U;
call(this: Function, thisArg: any, ...argArray: any[]): any;
/**
* For a given function, creates a bound function that has the same body as the original function.
@ -230,7 +232,8 @@ interface Function {
* @param thisArg An object to which the this keyword can refer inside the new function.
* @param argArray A list of arguments to be passed to the new function.
*/
bind(thisArg: any, ...argArray: any[]): any;
bind<T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, ...argArray: any[]): (this: void, ...argArray: any[]) => U;
bind(this: Function, thisArg: any, ...argArray: any[]): any;
prototype: any;
readonly length: number;
@ -3904,3 +3907,204 @@ interface Float64ArrayConstructor {
from(arrayLike: ArrayLike<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}
declare const Float64Array: Float64ArrayConstructor;
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. 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.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}

1333
src/lib/es6.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
/// <reference path="lib.core.d.ts" />

1
src/lib/importes5.d.ts vendored Normal file
View File

@ -0,0 +1 @@
/// <reference path="lib.es5.d.ts" />

201
src/lib/intl.d.ts vendored
View File

@ -1,201 +0,0 @@
/////////////////////////////
/// ECMAScript Internationalization API
/////////////////////////////
declare module Intl {
interface CollatorOptions {
usage?: string;
localeMatcher?: string;
numeric?: boolean;
caseFirst?: string;
sensitivity?: string;
ignorePunctuation?: boolean;
}
interface ResolvedCollatorOptions {
locale: string;
usage: string;
sensitivity: string;
ignorePunctuation: boolean;
collation: string;
caseFirst: string;
numeric: boolean;
}
interface Collator {
compare(x: string, y: string): number;
resolvedOptions(): ResolvedCollatorOptions;
}
var Collator: {
new (locales?: string[], options?: CollatorOptions): Collator;
new (locale?: string, options?: CollatorOptions): Collator;
(locales?: string[], options?: CollatorOptions): Collator;
(locale?: string, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: string[], options?: CollatorOptions): string[];
supportedLocalesOf(locale: string, options?: CollatorOptions): string[];
}
interface NumberFormatOptions {
localeMatcher?: string;
style?: string;
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumIntegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
locale: string;
numberingSystem: string;
style: string;
currency?: string;
currencyDisplay?: string;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
useGrouping: boolean;
}
interface NumberFormat {
format(value: number): string;
resolvedOptions(): ResolvedNumberFormatOptions;
}
var NumberFormat: {
new (locales?: string[], options?: NumberFormatOptions): NumberFormat;
new (locale?: string, options?: NumberFormatOptions): NumberFormat;
(locales?: string[], options?: NumberFormatOptions): NumberFormat;
(locale?: string, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: string[], options?: NumberFormatOptions): string[];
supportedLocalesOf(locale: string, options?: NumberFormatOptions): string[];
}
interface DateTimeFormatOptions {
localeMatcher?: string;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
formatMatcher?: string;
hour12?: boolean;
timeZone?: string;
}
interface ResolvedDateTimeFormatOptions {
locale: string;
calendar: string;
numberingSystem: string;
timeZone: string;
hour12?: boolean;
weekday?: string;
era?: string;
year?: string;
month?: string;
day?: string;
hour?: string;
minute?: string;
second?: string;
timeZoneName?: string;
}
interface DateTimeFormat {
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
new (locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
new (locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: string[], options?: DateTimeFormatOptions): DateTimeFormat;
(locale?: string, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: string[], options?: DateTimeFormatOptions): string[];
supportedLocalesOf(locale: string, options?: DateTimeFormatOptions): string[];
}
}
interface String {
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales: string[], options?: Intl.CollatorOptions): number;
/**
* Determines whether two strings are equivalent in the current locale.
* @param that String to compare to target string
* @param locale Locale tag. 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.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locale: string, options?: Intl.CollatorOptions): number;
}
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.NumberFormatOptions): string;
/**
* Converts a number to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.NumberFormatOptions): string;
}
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales An 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.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string[], options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locale Locale tag. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locale?: string, options?: Intl.DateTimeFormatOptions): string;
}

View File

@ -13,10 +13,12 @@ interface EventListener {
}
interface AudioBuffer {
duration: number;
length: number;
numberOfChannels: number;
sampleRate: number;
readonly duration: number;
readonly length: number;
readonly numberOfChannels: number;
readonly sampleRate: number;
copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void;
copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void;
getChannelData(channel: number): Float32Array;
}
@ -26,8 +28,8 @@ declare var AudioBuffer: {
}
interface Blob {
size: number;
type: string;
readonly size: number;
readonly type: string;
msClose(): void;
msDetachStream(): any;
slice(start?: number, end?: number, contentType?: string): Blob;
@ -39,9 +41,9 @@ declare var Blob: {
}
interface CloseEvent extends Event {
code: number;
reason: string;
wasClean: boolean;
readonly code: number;
readonly reason: string;
readonly wasClean: boolean;
initCloseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, wasCleanArg: boolean, codeArg: number, reasonArg: string): void;
}
@ -58,6 +60,7 @@ interface Console {
dir(value?: any, ...optionalParams: any[]): void;
dirxml(value: any): void;
error(message?: any, ...optionalParams: any[]): void;
exception(message?: string, ...optionalParams: any[]): void;
group(groupTitle?: string): void;
groupCollapsed(groupTitle?: string): void;
groupEnd(): void;
@ -67,6 +70,7 @@ interface Console {
profile(reportName?: string): void;
profileEnd(): void;
select(element: any): void;
table(...data: any[]): void;
time(timerName?: string): void;
timeEnd(timerName?: string): void;
trace(message?: any, ...optionalParams: any[]): void;
@ -79,13 +83,13 @@ declare var Console: {
}
interface Coordinates {
accuracy: number;
altitude: number;
altitudeAccuracy: number;
heading: number;
latitude: number;
longitude: number;
speed: number;
readonly accuracy: number;
readonly altitude: number;
readonly altitudeAccuracy: number;
readonly heading: number;
readonly latitude: number;
readonly longitude: number;
readonly speed: number;
}
declare var Coordinates: {
@ -94,7 +98,7 @@ declare var Coordinates: {
}
interface DOMError {
name: string;
readonly name: string;
toString(): string;
}
@ -104,73 +108,73 @@ declare var DOMError: {
}
interface DOMException {
code: number;
message: string;
name: string;
readonly code: number;
readonly message: string;
readonly name: string;
toString(): string;
ABORT_ERR: number;
DATA_CLONE_ERR: number;
DOMSTRING_SIZE_ERR: number;
HIERARCHY_REQUEST_ERR: number;
INDEX_SIZE_ERR: number;
INUSE_ATTRIBUTE_ERR: number;
INVALID_ACCESS_ERR: number;
INVALID_CHARACTER_ERR: number;
INVALID_MODIFICATION_ERR: number;
INVALID_NODE_TYPE_ERR: number;
INVALID_STATE_ERR: number;
NAMESPACE_ERR: number;
NETWORK_ERR: number;
NOT_FOUND_ERR: number;
NOT_SUPPORTED_ERR: number;
NO_DATA_ALLOWED_ERR: number;
NO_MODIFICATION_ALLOWED_ERR: number;
PARSE_ERR: number;
QUOTA_EXCEEDED_ERR: number;
SECURITY_ERR: number;
SERIALIZE_ERR: number;
SYNTAX_ERR: number;
TIMEOUT_ERR: number;
TYPE_MISMATCH_ERR: number;
URL_MISMATCH_ERR: number;
VALIDATION_ERR: number;
WRONG_DOCUMENT_ERR: number;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
declare var DOMException: {
prototype: DOMException;
new(): DOMException;
ABORT_ERR: number;
DATA_CLONE_ERR: number;
DOMSTRING_SIZE_ERR: number;
HIERARCHY_REQUEST_ERR: number;
INDEX_SIZE_ERR: number;
INUSE_ATTRIBUTE_ERR: number;
INVALID_ACCESS_ERR: number;
INVALID_CHARACTER_ERR: number;
INVALID_MODIFICATION_ERR: number;
INVALID_NODE_TYPE_ERR: number;
INVALID_STATE_ERR: number;
NAMESPACE_ERR: number;
NETWORK_ERR: number;
NOT_FOUND_ERR: number;
NOT_SUPPORTED_ERR: number;
NO_DATA_ALLOWED_ERR: number;
NO_MODIFICATION_ALLOWED_ERR: number;
PARSE_ERR: number;
QUOTA_EXCEEDED_ERR: number;
SECURITY_ERR: number;
SERIALIZE_ERR: number;
SYNTAX_ERR: number;
TIMEOUT_ERR: number;
TYPE_MISMATCH_ERR: number;
URL_MISMATCH_ERR: number;
VALIDATION_ERR: number;
WRONG_DOCUMENT_ERR: number;
readonly ABORT_ERR: number;
readonly DATA_CLONE_ERR: number;
readonly DOMSTRING_SIZE_ERR: number;
readonly HIERARCHY_REQUEST_ERR: number;
readonly INDEX_SIZE_ERR: number;
readonly INUSE_ATTRIBUTE_ERR: number;
readonly INVALID_ACCESS_ERR: number;
readonly INVALID_CHARACTER_ERR: number;
readonly INVALID_MODIFICATION_ERR: number;
readonly INVALID_NODE_TYPE_ERR: number;
readonly INVALID_STATE_ERR: number;
readonly NAMESPACE_ERR: number;
readonly NETWORK_ERR: number;
readonly NOT_FOUND_ERR: number;
readonly NOT_SUPPORTED_ERR: number;
readonly NO_DATA_ALLOWED_ERR: number;
readonly NO_MODIFICATION_ALLOWED_ERR: number;
readonly PARSE_ERR: number;
readonly QUOTA_EXCEEDED_ERR: number;
readonly SECURITY_ERR: number;
readonly SERIALIZE_ERR: number;
readonly SYNTAX_ERR: number;
readonly TIMEOUT_ERR: number;
readonly TYPE_MISMATCH_ERR: number;
readonly URL_MISMATCH_ERR: number;
readonly VALIDATION_ERR: number;
readonly WRONG_DOCUMENT_ERR: number;
}
interface DOMStringList {
length: number;
readonly length: number;
contains(str: string): boolean;
item(index: number): string;
[index: number]: string;
@ -182,11 +186,11 @@ declare var DOMStringList: {
}
interface ErrorEvent extends Event {
colno: number;
error: any;
filename: string;
lineno: number;
message: string;
readonly colno: number;
readonly error: any;
readonly filename: string;
readonly lineno: number;
readonly message: string;
initErrorEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, messageArg: string, filenameArg: string, linenoArg: number): void;
}
@ -196,39 +200,39 @@ declare var ErrorEvent: {
}
interface Event {
bubbles: boolean;
readonly bubbles: boolean;
cancelBubble: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
readonly cancelable: boolean;
readonly currentTarget: EventTarget;
readonly defaultPrevented: boolean;
readonly eventPhase: number;
readonly isTrusted: boolean;
returnValue: boolean;
srcElement: any;
target: EventTarget;
timeStamp: number;
type: string;
readonly srcElement: any;
readonly target: EventTarget;
readonly timeStamp: number;
readonly type: string;
initEvent(eventTypeArg: string, canBubbleArg: boolean, cancelableArg: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
declare var Event: {
prototype: Event;
new(type: string, eventInitDict?: EventInit): Event;
AT_TARGET: number;
BUBBLING_PHASE: number;
CAPTURING_PHASE: number;
readonly AT_TARGET: number;
readonly BUBBLING_PHASE: number;
readonly CAPTURING_PHASE: number;
}
interface EventTarget {
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
dispatchEvent(evt: Event): boolean;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var EventTarget: {
@ -237,8 +241,9 @@ declare var EventTarget: {
}
interface File extends Blob {
lastModifiedDate: any;
name: string;
readonly lastModifiedDate: any;
readonly name: string;
readonly webkitRelativePath: string;
}
declare var File: {
@ -247,7 +252,7 @@ declare var File: {
}
interface FileList {
length: number;
readonly length: number;
item(index: number): File;
[index: number]: File;
}
@ -258,7 +263,7 @@ declare var FileList: {
}
interface FileReader extends EventTarget, MSBaseReader {
error: DOMError;
readonly error: DOMError;
readAsArrayBuffer(blob: Blob): void;
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): void;
@ -272,31 +277,31 @@ declare var FileReader: {
}
interface IDBCursor {
direction: string;
key: any;
primaryKey: any;
readonly direction: string;
key: IDBKeyRange | IDBValidKey;
readonly primaryKey: any;
source: IDBObjectStore | IDBIndex;
advance(count: number): void;
continue(key?: any): void;
continue(key?: IDBKeyRange | IDBValidKey): void;
delete(): IDBRequest;
update(value: any): IDBRequest;
NEXT: string;
NEXT_NO_DUPLICATE: string;
PREV: string;
PREV_NO_DUPLICATE: string;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
declare var IDBCursor: {
prototype: IDBCursor;
new(): IDBCursor;
NEXT: string;
NEXT_NO_DUPLICATE: string;
PREV: string;
PREV_NO_DUPLICATE: string;
readonly NEXT: string;
readonly NEXT_NO_DUPLICATE: string;
readonly PREV: string;
readonly PREV_NO_DUPLICATE: string;
}
interface IDBCursorWithValue extends IDBCursor {
value: any;
readonly value: any;
}
declare var IDBCursorWithValue: {
@ -305,15 +310,17 @@ declare var IDBCursorWithValue: {
}
interface IDBDatabase extends EventTarget {
name: string;
objectStoreNames: DOMStringList;
readonly name: string;
readonly objectStoreNames: DOMStringList;
onabort: (ev: Event) => any;
onerror: (ev: Event) => any;
version: number;
onversionchange: (ev: IDBVersionChangeEvent) => any;
close(): void;
createObjectStore(name: string, optionalParameters?: IDBObjectStoreParameters): IDBObjectStore;
deleteObjectStore(name: string): void;
transaction(storeNames: string | string[], mode?: string): IDBTransaction;
addEventListener(type: "versionchange", listener: (ev: IDBVersionChangeEvent) => any, useCapture?: boolean): void;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -337,15 +344,15 @@ declare var IDBFactory: {
interface IDBIndex {
keyPath: string | string[];
name: string;
objectStore: IDBObjectStore;
unique: boolean;
readonly name: string;
readonly objectStore: IDBObjectStore;
readonly unique: boolean;
multiEntry: boolean;
count(key?: any): IDBRequest;
get(key: any): IDBRequest;
getKey(key: any): IDBRequest;
openCursor(range?: IDBKeyRange, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange, direction?: string): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
get(key: IDBKeyRange | IDBValidKey): IDBRequest;
getKey(key: IDBKeyRange | IDBValidKey): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
openKeyCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
}
declare var IDBIndex: {
@ -354,37 +361,37 @@ declare var IDBIndex: {
}
interface IDBKeyRange {
lower: any;
lowerOpen: boolean;
upper: any;
upperOpen: boolean;
readonly lower: any;
readonly lowerOpen: boolean;
readonly upper: any;
readonly upperOpen: boolean;
}
declare var IDBKeyRange: {
prototype: IDBKeyRange;
new(): IDBKeyRange;
bound(lower: any, upper: any, lowerOpen?: boolean, upperOpen?: boolean): IDBKeyRange;
lowerBound(bound: any, open?: boolean): IDBKeyRange;
lowerBound(lower: any, open?: boolean): IDBKeyRange;
only(value: any): IDBKeyRange;
upperBound(bound: any, open?: boolean): IDBKeyRange;
upperBound(upper: any, open?: boolean): IDBKeyRange;
}
interface IDBObjectStore {
indexNames: DOMStringList;
readonly indexNames: DOMStringList;
keyPath: string | string[];
name: string;
transaction: IDBTransaction;
readonly name: string;
readonly transaction: IDBTransaction;
autoIncrement: boolean;
add(value: any, key?: any): IDBRequest;
add(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
clear(): IDBRequest;
count(key?: any): IDBRequest;
count(key?: IDBKeyRange | IDBValidKey): IDBRequest;
createIndex(name: string, keyPath: string | string[], optionalParameters?: IDBIndexParameters): IDBIndex;
delete(key: any): IDBRequest;
delete(key: IDBKeyRange | IDBValidKey): IDBRequest;
deleteIndex(indexName: string): void;
get(key: any): IDBRequest;
index(name: string): IDBIndex;
openCursor(range?: any, direction?: string): IDBRequest;
put(value: any, key?: any): IDBRequest;
openCursor(range?: IDBKeyRange | IDBValidKey, direction?: string): IDBRequest;
put(value: any, key?: IDBKeyRange | IDBValidKey): IDBRequest;
}
declare var IDBObjectStore: {
@ -408,13 +415,13 @@ declare var IDBOpenDBRequest: {
}
interface IDBRequest extends EventTarget {
error: DOMError;
readonly error: DOMError;
onerror: (ev: Event) => any;
onsuccess: (ev: Event) => any;
readyState: string;
result: any;
readonly readyState: string;
readonly result: any;
source: IDBObjectStore | IDBIndex | IDBCursor;
transaction: IDBTransaction;
readonly transaction: IDBTransaction;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "success", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -426,17 +433,17 @@ declare var IDBRequest: {
}
interface IDBTransaction extends EventTarget {
db: IDBDatabase;
error: DOMError;
mode: string;
readonly db: IDBDatabase;
readonly error: DOMError;
readonly mode: string;
onabort: (ev: Event) => any;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
abort(): void;
objectStore(name: string): IDBObjectStore;
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
@ -446,14 +453,14 @@ interface IDBTransaction extends EventTarget {
declare var IDBTransaction: {
prototype: IDBTransaction;
new(): IDBTransaction;
READ_ONLY: string;
READ_WRITE: string;
VERSION_CHANGE: string;
readonly READ_ONLY: string;
readonly READ_WRITE: string;
readonly VERSION_CHANGE: string;
}
interface IDBVersionChangeEvent extends Event {
newVersion: number;
oldVersion: number;
readonly newVersion: number;
readonly oldVersion: number;
}
declare var IDBVersionChangeEvent: {
@ -463,8 +470,8 @@ declare var IDBVersionChangeEvent: {
interface ImageData {
data: Uint8ClampedArray;
height: number;
width: number;
readonly height: number;
readonly width: number;
}
declare var ImageData: {
@ -483,29 +490,29 @@ interface MSApp {
execAsyncAtPriority(asynchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): void;
execAtPriority(synchronousCallback: MSExecAtPriorityFunctionCallback, priority: string, ...args: any[]): any;
getCurrentPriority(): string;
getHtmlPrintDocumentSourceAsync(htmlDoc: any): any;
getHtmlPrintDocumentSourceAsync(htmlDoc: any): PromiseLike<any>;
getViewId(view: any): any;
isTaskScheduledAtPriorityOrHigher(priority: string): boolean;
pageHandlesAllApplicationActivations(enabled: boolean): void;
suppressSubdownloadCredentialPrompts(suppress: boolean): void;
terminateApp(exceptionObject: any): void;
CURRENT: string;
HIGH: string;
IDLE: string;
NORMAL: string;
readonly CURRENT: string;
readonly HIGH: string;
readonly IDLE: string;
readonly NORMAL: string;
}
declare var MSApp: MSApp;
interface MSAppAsyncOperation extends EventTarget {
error: DOMError;
readonly error: DOMError;
oncomplete: (ev: Event) => any;
onerror: (ev: Event) => any;
readyState: number;
result: any;
readonly readyState: number;
readonly result: any;
start(): void;
COMPLETED: number;
ERROR: number;
STARTED: number;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
addEventListener(type: "complete", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
@ -514,9 +521,9 @@ interface MSAppAsyncOperation extends EventTarget {
declare var MSAppAsyncOperation: {
prototype: MSAppAsyncOperation;
new(): MSAppAsyncOperation;
COMPLETED: number;
ERROR: number;
STARTED: number;
readonly COMPLETED: number;
readonly ERROR: number;
readonly STARTED: number;
}
interface MSBlobBuilder {
@ -530,7 +537,7 @@ declare var MSBlobBuilder: {
}
interface MSStream {
type: string;
readonly type: string;
msClose(): void;
msDetachStream(): any;
}
@ -541,7 +548,7 @@ declare var MSStream: {
}
interface MSStreamReader extends EventTarget, MSBaseReader {
error: DOMError;
readonly error: DOMError;
readAsArrayBuffer(stream: MSStream, size?: number): void;
readAsBinaryString(stream: MSStream, size?: number): void;
readAsBlob(stream: MSStream, size?: number): void;
@ -556,8 +563,8 @@ declare var MSStreamReader: {
}
interface MediaQueryList {
matches: boolean;
media: string;
readonly matches: boolean;
readonly media: string;
addListener(listener: MediaQueryListListener): void;
removeListener(listener: MediaQueryListListener): void;
}
@ -568,8 +575,8 @@ declare var MediaQueryList: {
}
interface MessageChannel {
port1: MessagePort;
port2: MessagePort;
readonly port1: MessagePort;
readonly port2: MessagePort;
}
declare var MessageChannel: {
@ -578,10 +585,10 @@ declare var MessageChannel: {
}
interface MessageEvent extends Event {
data: any;
origin: string;
ports: any;
source: any;
readonly data: any;
readonly origin: string;
readonly ports: any;
readonly source: any;
initMessageEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, dataArg: any, originArg: string, lastEventIdArg: string, sourceArg: any): void;
}
@ -605,8 +612,8 @@ declare var MessagePort: {
}
interface Position {
coords: Coordinates;
timestamp: number;
readonly coords: Coordinates;
readonly timestamp: number;
}
declare var Position: {
@ -615,26 +622,26 @@ declare var Position: {
}
interface PositionError {
code: number;
message: string;
readonly code: number;
readonly message: string;
toString(): string;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
declare var PositionError: {
prototype: PositionError;
new(): PositionError;
PERMISSION_DENIED: number;
POSITION_UNAVAILABLE: number;
TIMEOUT: number;
readonly PERMISSION_DENIED: number;
readonly POSITION_UNAVAILABLE: number;
readonly TIMEOUT: number;
}
interface ProgressEvent extends Event {
lengthComputable: boolean;
loaded: number;
total: number;
readonly lengthComputable: boolean;
readonly loaded: number;
readonly total: number;
initProgressEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, lengthComputableArg: boolean, loadedArg: number, totalArg: number): void;
}
@ -645,21 +652,21 @@ declare var ProgressEvent: {
interface WebSocket extends EventTarget {
binaryType: string;
bufferedAmount: number;
extensions: string;
readonly bufferedAmount: number;
readonly extensions: string;
onclose: (ev: CloseEvent) => any;
onerror: (ev: Event) => any;
onmessage: (ev: MessageEvent) => any;
onopen: (ev: Event) => any;
protocol: string;
readyState: number;
url: string;
readonly protocol: string;
readonly readyState: number;
readonly url: string;
close(code?: number, reason?: string): void;
send(data: any): void;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
OPEN: number;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
@ -670,10 +677,10 @@ interface WebSocket extends EventTarget {
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
CLOSED: number;
CLOSING: number;
CONNECTING: number;
OPEN: number;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
}
interface Worker extends EventTarget, AbstractWorker {
@ -693,16 +700,15 @@ declare var Worker: {
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
msCaching: string;
onreadystatechange: (ev: ProgressEvent) => any;
readyState: number;
response: any;
responseBody: any;
responseText: string;
readonly readyState: number;
readonly response: any;
readonly responseText: string;
responseType: string;
responseXML: any;
status: number;
statusText: string;
readonly responseXML: any;
readonly status: number;
readonly statusText: string;
timeout: number;
upload: XMLHttpRequestUpload;
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
abort(): void;
getAllResponseHeaders(): string;
@ -713,11 +719,11 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
send(data?: string): void;
send(data?: any): void;
setRequestHeader(header: string, value: string): void;
DONE: number;
HEADERS_RECEIVED: number;
LOADING: number;
OPENED: number;
UNSENT: number;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
@ -732,11 +738,11 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
declare var XMLHttpRequest: {
prototype: XMLHttpRequest;
new(): XMLHttpRequest;
DONE: number;
HEADERS_RECEIVED: number;
LOADING: number;
OPENED: number;
UNSENT: number;
readonly DONE: number;
readonly HEADERS_RECEIVED: number;
readonly LOADING: number;
readonly OPENED: number;
readonly UNSENT: number;
create(): XMLHttpRequest;
}
@ -762,12 +768,12 @@ interface MSBaseReader {
onloadend: (ev: ProgressEvent) => any;
onloadstart: (ev: Event) => any;
onprogress: (ev: ProgressEvent) => any;
readyState: number;
result: any;
readonly readyState: number;
readonly result: any;
abort(): void;
DONE: number;
EMPTY: number;
LOADING: number;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: number;
addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
@ -778,18 +784,18 @@ interface MSBaseReader {
}
interface NavigatorID {
appName: string;
appVersion: string;
platform: string;
product: string;
productSub: string;
userAgent: string;
vendor: string;
vendorSub: string;
readonly appName: string;
readonly appVersion: string;
readonly platform: string;
readonly product: string;
readonly productSub: string;
readonly userAgent: string;
readonly vendor: string;
readonly vendorSub: string;
}
interface NavigatorOnLine {
onLine: boolean;
readonly onLine: boolean;
}
interface WindowBase64 {
@ -798,7 +804,7 @@ interface WindowBase64 {
}
interface WindowConsole {
console: Console;
readonly console: Console;
}
interface XMLHttpRequestEventTarget {
@ -832,9 +838,9 @@ declare var FileReaderSync: {
}
interface WorkerGlobalScope extends EventTarget, WorkerUtils, DedicatedWorkerGlobalScope, WindowConsole {
location: WorkerLocation;
readonly location: WorkerLocation;
onerror: (ev: Event) => any;
self: WorkerGlobalScope;
readonly self: WorkerGlobalScope;
close(): void;
msWriteProfilerMark(profilerMarkName: string): void;
toString(): string;
@ -849,14 +855,14 @@ declare var WorkerGlobalScope: {
}
interface WorkerLocation {
hash: string;
host: string;
hostname: string;
href: string;
pathname: string;
port: string;
protocol: string;
search: string;
readonly hash: string;
readonly host: string;
readonly hostname: string;
readonly href: string;
readonly pathname: string;
readonly port: string;
readonly protocol: string;
readonly search: string;
toString(): string;
}
@ -882,9 +888,9 @@ interface DedicatedWorkerGlobalScope {
}
interface WorkerUtils extends Object, WindowBase64 {
indexedDB: IDBFactory;
msIndexedDB: IDBFactory;
navigator: WorkerNavigator;
readonly indexedDB: IDBFactory;
readonly msIndexedDB: IDBFactory;
readonly navigator: WorkerNavigator;
clearImmediate(handle: number): void;
clearInterval(handle: number): void;
clearTimeout(handle: number): void;
@ -894,16 +900,6 @@ interface WorkerUtils extends Object, WindowBase64 {
setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}
interface IDBObjectStoreParameters {
keyPath?: string | string[];
autoIncrement?: boolean;
}
interface IDBIndexParameters {
unique?: boolean;
multiEntry?: boolean;
}
interface BlobPropertyBag {
type?: string;
endings?: string;
@ -933,6 +929,9 @@ interface ProgressEventInit extends EventInit {
total?: number;
}
interface IDBArrayKey extends Array<IDBValidKey> {
}
declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;
interface ErrorEventHandler {
@ -971,9 +970,9 @@ declare var self: WorkerGlobalScope;
declare function close(): void;
declare function msWriteProfilerMark(profilerMarkName: string): void;
declare function toString(): string;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function dispatchEvent(evt: Event): boolean;
declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function removeEventListener(type: string, listener?: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare var indexedDB: IDBFactory;
declare var msIndexedDB: IDBFactory;
declare var navigator: WorkerNavigator;
@ -991,4 +990,5 @@ declare function postMessage(data: any): void;
declare var console: Console;
declare function addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
type IDBValidKey = number | string | Date | IDBArrayKey;

View File

@ -81,8 +81,14 @@ namespace ts.server {
}
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations {
lastCheckTime: number;
interface Timestamped {
lastCheckTime?: number;
}
interface TimestampedResolvedModule extends ResolvedModuleWithFailedLookupLocations, Timestamped {
}
interface TimestampedResolvedTypeReferenceDirective extends ResolvedTypeReferenceDirectiveWithFailedLookupLocations, Timestamped {
}
export class LSHost implements ts.LanguageServiceHost {
@ -90,13 +96,16 @@ namespace ts.server {
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.FileMap<ScriptInfo>;
roots: ScriptInfo[] = [];
private resolvedModuleNames: ts.FileMap<Map<TimestampedResolvedModule>>;
private resolvedTypeReferenceDirectives: ts.FileMap<Map<TimestampedResolvedTypeReferenceDirective>>;
private moduleResolutionHost: ts.ModuleResolutionHost;
private getCanonicalFileName: (fileName: string) => string;
constructor(public host: ServerHost, public project: Project) {
this.getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames);
this.resolvedModuleNames = createFileMap<Map<TimestampedResolvedModule>>();
this.resolvedTypeReferenceDirectives = createFileMap<Map<TimestampedResolvedTypeReferenceDirective>>();
this.filenameToScript = createFileMap<ScriptInfo>();
this.moduleResolutionHost = {
fileExists: fileName => this.fileExists(fileName),
@ -105,46 +114,51 @@ namespace ts.server {
};
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
private resolveNamesWithLocalCache<T extends Timestamped & { failedLookupLocations: string[] }, R>(
names: string[],
containingFile: string,
cache: ts.FileMap<Map<T>>,
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T,
getResult: (s: T) => R): R[] {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = this.resolvedModuleNames.get(path);
const newResolutions: Map<TimestampedResolvedModule> = {};
const resolvedModules: ResolvedModule[] = [];
const currentResolutionsInFile = cache.get(path);
const newResolutions: Map<T> = {};
const resolvedModules: R[] = [];
const compilerOptions = this.getCompilationSettings();
for (const moduleName of moduleNames) {
for (const name of names) {
// check if this is a duplicate entry in the list
let resolution = lookUp(newResolutions, moduleName);
let resolution = lookUp(newResolutions, name);
if (!resolution) {
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, moduleName);
const existingResolution = currentResolutionsInFile && ts.lookUp(currentResolutionsInFile, name);
if (moduleResolutionIsValid(existingResolution)) {
// ok, it is safe to use existing module resolution results
// ok, it is safe to use existing name resolution results
resolution = existingResolution;
}
else {
resolution = <TimestampedResolvedModule>resolveModuleName(moduleName, containingFile, compilerOptions, this.moduleResolutionHost);
resolution = loader(name, containingFile, compilerOptions, this.moduleResolutionHost);
resolution.lastCheckTime = Date.now();
newResolutions[moduleName] = resolution;
newResolutions[name] = resolution;
}
}
ts.Debug.assert(resolution !== undefined);
resolvedModules.push(resolution.resolvedModule);
resolvedModules.push(getResult(resolution));
}
// replace old results with a new one
this.resolvedModuleNames.set(path, newResolutions);
cache.set(path, newResolutions);
return resolvedModules;
function moduleResolutionIsValid(resolution: TimestampedResolvedModule): boolean {
function moduleResolutionIsValid(resolution: T): boolean {
if (!resolution) {
return false;
}
if (resolution.resolvedModule) {
if (getResult(resolution)) {
// TODO: consider checking failedLookupLocations
// TODO: use lastCheckTime to track expiration for module name resolution
return true;
@ -156,6 +170,14 @@ namespace ts.server {
}
}
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective, m => m.resolvedTypeReferenceDirective);
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, resolveModuleName, m => m.resolvedModule);
}
getDefaultLibFileName() {
const nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath()));
return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings));
@ -172,6 +194,7 @@ namespace ts.server {
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
this.resolvedTypeReferenceDirectives.clear();
}
lineAffectsRefs(filename: string, line: number) {
@ -212,6 +235,7 @@ namespace ts.server {
if (!info.isOpen) {
this.filenameToScript.remove(info.path);
this.resolvedModuleNames.remove(info.path);
this.resolvedTypeReferenceDirectives.remove(info.path);
}
}
@ -239,6 +263,7 @@ namespace ts.server {
this.filenameToScript.remove(info.path);
this.roots = copyListRemovingItem(info, this.roots);
this.resolvedModuleNames.remove(info.path);
this.resolvedTypeReferenceDirectives.remove(info.path);
}
}

View File

@ -1,7 +1,7 @@
/// <reference path="node.d.ts" />
/// <reference path="session.ts" />
// used in fs.writeSync
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
namespace ts.server {
const readline: NodeJS.ReadLine = require("readline");

View File

@ -125,6 +125,7 @@ namespace ts {
}
export interface PreProcessedFileInfo {
referencedFiles: FileReference[];
typeReferenceDirectives: FileReference[];
importedFiles: FileReference[];
ambientExternalModules: string[];
isLibFile: boolean;
@ -762,6 +763,7 @@ namespace ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
thisType: Type;
resolvedReturnType: Type;
minArgumentCount: number;
hasRestParameter: boolean;
@ -813,6 +815,7 @@ namespace ts {
public amdDependencies: { name: string; path: string }[];
public moduleName: string;
public referencedFiles: FileReference[];
public typeReferenceDirectives: FileReference[];
public syntacticDiagnostics: Diagnostic[];
public referenceDiagnostics: Diagnostic[];
@ -834,6 +837,7 @@ namespace ts {
public identifiers: Map<string>;
public nameTable: Map<number>;
public resolvedModules: Map<ResolvedModule>;
public resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
public imports: LiteralExpression[];
public moduleAugmentations: LiteralExpression[];
private namedDeclarations: Map<Declaration[]>;
@ -1060,6 +1064,7 @@ namespace ts {
* host specific questions using 'getScriptSnapshot'.
*/
resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[];
resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[];
directoryExists?(directoryName: string): boolean;
}
@ -2167,6 +2172,7 @@ namespace ts {
export function preProcessFile(sourceText: string, readImportFiles = true, detectJavaScriptImports = false): PreProcessedFileInfo {
const referencedFiles: FileReference[] = [];
const typeReferenceDirectives: FileReference[] = [];
const importedFiles: FileReference[] = [];
let ambientExternalModules: { ref: FileReference, depth: number }[];
let isNoDefaultLib = false;
@ -2195,7 +2201,11 @@ namespace ts {
isNoDefaultLib = referencePathMatchResult.isNoDefaultLib;
const fileReference = referencePathMatchResult.fileReference;
if (fileReference) {
referencedFiles.push(fileReference);
const collection = referencePathMatchResult.isTypeReferenceDirective
? typeReferenceDirectives
: referencedFiles;
collection.push(fileReference);
}
}
});
@ -2496,7 +2506,7 @@ namespace ts {
importedFiles.push(decl.ref);
}
}
return { referencedFiles, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
return { referencedFiles, typeReferenceDirectives, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: undefined };
}
else {
// for global scripts ambient modules still can have augmentations - look for ambient modules with depth > 0
@ -2514,7 +2524,7 @@ namespace ts {
}
}
}
return { referencedFiles, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
return { referencedFiles, typeReferenceDirectives, importedFiles, isLibFile: isNoDefaultLib, ambientExternalModules: ambientModuleNames };
}
}
@ -2851,7 +2861,7 @@ namespace ts {
getCurrentDirectory: () => currentDirectory,
fileExists: (fileName): boolean => {
// stub missing host functionality
Debug.assert(!host.resolveModuleNames);
Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives);
return hostCache.getOrCreateEntry(fileName) !== undefined;
},
readFile: (fileName): string => {
@ -2860,7 +2870,7 @@ namespace ts {
return entry && entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength());
},
directoryExists: directoryName => {
Debug.assert(!host.resolveModuleNames);
Debug.assert(!host.resolveModuleNames || !host.resolveTypeReferenceDirectives);
return directoryProbablyExists(directoryName, host);
}
};
@ -2871,6 +2881,11 @@ namespace ts {
if (host.resolveModuleNames) {
compilerHost.resolveModuleNames = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile);
}
if (host.resolveTypeReferenceDirectives) {
compilerHost.resolveTypeReferenceDirectives = (typeReferenceDirectiveNames, containingFile) => {
return host.resolveTypeReferenceDirectives(typeReferenceDirectiveNames, containingFile);
};
}
const newProgram = createProgram(hostCache.getRootFileNames(), newSettings, compilerHost, program);
@ -3840,10 +3855,10 @@ namespace ts {
}
if (isEmpty(existingImportsOrExports)) {
return exportsOfModule;
return filter(exportsOfModule, e => e.name !== "default");
}
return filter(exportsOfModule, e => !lookUp(existingImportsOrExports, e.name));
return filter(exportsOfModule, e => e.name !== "default" && !lookUp(existingImportsOrExports, e.name));
}
/**
@ -4130,6 +4145,9 @@ namespace ts {
if (typeChecker.isArgumentsSymbol(symbol)) {
return ScriptElementKind.localVariableElement;
}
if (location.kind === SyntaxKind.ThisKeyword && isExpression(location)) {
return ScriptElementKind.parameterElement;
}
if (flags & SymbolFlags.Variable) {
if (isFirstDeclarationOfSymbolParameter(symbol)) {
return ScriptElementKind.parameterElement;
@ -4192,6 +4210,7 @@ namespace ts {
const symbolFlags = symbol.flags;
let symbolKind = getSymbolKindOfConstructorPropertyMethodAccessorFunctionOrVar(symbol, symbolFlags, location);
let hasAddedSymbolInfo: boolean;
const isThisExpression: boolean = location.kind === SyntaxKind.ThisKeyword && isExpression(location);
let type: Type;
// Class at constructor site need to be shown as constructor apart from property,method, vars
@ -4202,7 +4221,7 @@ namespace ts {
}
let signature: Signature;
type = typeChecker.getTypeOfSymbolAtLocation(symbol, location);
type = isThisExpression ? typeChecker.getTypeAtLocation(location) : typeChecker.getTypeOfSymbolAtLocation(symbol, location);
if (type) {
if (location.parent && location.parent.kind === SyntaxKind.PropertyAccessExpression) {
const right = (<PropertyAccessExpression>location.parent).name;
@ -4313,7 +4332,7 @@ namespace ts {
}
}
}
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo) {
if (symbolFlags & SymbolFlags.Class && !hasAddedSymbolInfo && !isThisExpression) {
if (getDeclarationOfKind(symbol, SyntaxKind.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)
@ -4455,11 +4474,19 @@ namespace ts {
if (!hasAddedSymbolInfo) {
if (symbolKind !== ScriptElementKind.unknown) {
if (type) {
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
if (isThisExpression) {
addNewLineIfDisplayPartsExist();
displayParts.push(keywordPart(SyntaxKind.ThisKeyword));
}
else {
addPrefixForAnyFunctionOrVar(symbol, symbolKind);
}
// For properties, variables and local vars: show the type
if (symbolKind === ScriptElementKind.memberVariableElement ||
symbolFlags & SymbolFlags.Variable ||
symbolKind === ScriptElementKind.localVariableElement) {
symbolKind === ScriptElementKind.localVariableElement ||
isThisExpression) {
displayParts.push(punctuationPart(SyntaxKind.ColonToken));
displayParts.push(spacePart());
// If the type is type parameter, format it specially
@ -4691,6 +4718,26 @@ namespace ts {
}
}
function findReferenceInPosition(refs: FileReference[], pos: number): FileReference {
for (const ref of refs) {
if (ref.pos <= pos && pos < ref.end) {
return ref;
}
}
return undefined;
}
function getDefinitionInfoForFileReference(name: string, targetFileName: string): DefinitionInfo {
return {
fileName: targetFileName,
textSpan: createTextSpanFromBounds(0, 0),
kind: ScriptElementKind.scriptElement,
name: name,
containerName: undefined,
containerKind: undefined
};
}
/// Goto definition
function getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[] {
synchronizeHostData();
@ -4710,18 +4757,20 @@ namespace ts {
}
/// Triple slash reference comments
const comment = forEach(sourceFile.referencedFiles, r => (r.pos <= position && position < r.end) ? r : undefined);
const comment = findReferenceInPosition(sourceFile.referencedFiles, position);
if (comment) {
const referenceFile = tryResolveScriptReference(program, sourceFile, comment);
if (referenceFile) {
return [{
fileName: referenceFile.fileName,
textSpan: createTextSpanFromBounds(0, 0),
kind: ScriptElementKind.scriptElement,
name: comment.fileName,
containerName: undefined,
containerKind: undefined
}];
return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)];
}
return undefined;
}
// Type reference directives
const typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position);
if (typeReferenceDirective) {
const referenceFile = lookUp(program.getResolvedTypeReferenceDirectives(), typeReferenceDirective.fileName);
if (referenceFile && referenceFile.resolvedFileName) {
return [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)];
}
return undefined;
}
@ -5632,8 +5681,51 @@ namespace ts {
};
}
function isImportSpecifierSymbol(symbol: Symbol) {
return (symbol.flags & SymbolFlags.Alias) && !!getDeclarationOfKind(symbol, SyntaxKind.ImportSpecifier);
function getAliasSymbolForPropertyNameSymbol(symbol: Symbol, location: Node): Symbol {
if (symbol.flags & SymbolFlags.Alias) {
// Default import get alias
const defaultImport = getDeclarationOfKind(symbol, SyntaxKind.ImportClause);
if (defaultImport) {
return typeChecker.getAliasedSymbol(symbol);
}
const importOrExportSpecifier = <ImportOrExportSpecifier>forEach(symbol.declarations,
declaration => (declaration.kind === SyntaxKind.ImportSpecifier ||
declaration.kind === SyntaxKind.ExportSpecifier) ? declaration : undefined);
if (importOrExportSpecifier &&
// export { a }
(!importOrExportSpecifier.propertyName ||
// export {a as class } where a is location
importOrExportSpecifier.propertyName === location)) {
// If Import specifier -> get alias
// else Export specifier -> get local target
return importOrExportSpecifier.kind === SyntaxKind.ImportSpecifier ?
typeChecker.getAliasedSymbol(symbol) :
typeChecker.getExportSpecifierLocalTargetSymbol(importOrExportSpecifier);
}
}
return undefined;
}
function getPropertySymbolOfDestructuringAssignment(location: Node) {
return isArrayLiteralOrObjectLiteralDestructuringPattern(location.parent.parent) &&
typeChecker.getPropertySymbolOfDestructuringAssignment(<Identifier>location);
}
function isObjectBindingPatternElementWithoutPropertyName(symbol: Symbol) {
const bindingElement = <BindingElement>getDeclarationOfKind(symbol, SyntaxKind.BindingElement);
return bindingElement &&
bindingElement.parent.kind === SyntaxKind.ObjectBindingPattern &&
!bindingElement.propertyName;
}
function getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol: Symbol) {
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
const bindingElement = <BindingElement>getDeclarationOfKind(symbol, SyntaxKind.BindingElement);
const typeOfPattern = typeChecker.getTypeAtLocation(bindingElement.parent);
return typeOfPattern && typeChecker.getPropertyOfType(typeOfPattern, (<Identifier>bindingElement.name).text);
}
return undefined;
}
function getInternedName(symbol: Symbol, location: Node, declarations: Declaration[]): string {
@ -5681,6 +5773,12 @@ namespace ts {
return undefined;
}
// If symbol is of object binding pattern element without property name we would want to
// look for property too and that could be anywhere
if (isObjectBindingPatternElementWithoutPropertyName(symbol)) {
return undefined;
}
// if this symbol is visible from its parent container, e.g. exported, then bail out
// if symbol correspond to the union property - bail out
if (symbol.parent || (symbol.flags & SymbolFlags.SyntheticProperty)) {
@ -6077,18 +6175,30 @@ namespace ts {
// The search set contains at least the current symbol
let result = [symbol];
// If the symbol is an alias, add what it aliases to the list
if (isImportSpecifierSymbol(symbol)) {
result.push(typeChecker.getAliasedSymbol(symbol));
// If the location is name of property symbol from object literal destructuring pattern
// Search the property symbol
// for ( { property: p2 } of elems) { }
if (isNameOfPropertyAssignment(location) && location.parent.kind !== SyntaxKind.ShorthandPropertyAssignment) {
const propertySymbol = getPropertySymbolOfDestructuringAssignment(location);
if (propertySymbol) {
result.push(propertySymbol);
}
}
// For export specifiers, the exported name can be referring to a local symbol, e.g.:
// If the symbol is an alias, add what it aliases to the list
// import {a} from "mod";
// export {a as somethingElse}
// We want the *local* declaration of 'a' as declared in the import,
// *not* as declared within "mod" (or farther)
if (location.parent.kind === SyntaxKind.ExportSpecifier) {
result.push(typeChecker.getExportSpecifierLocalTargetSymbol(<ExportSpecifier>location.parent));
// export {a}
// If the symbol is an alias to default declaration, add what it aliases to the list
// declare "mod" { export default class B { } }
// import B from "mod";
//// For export specifiers, the exported name can be referring to a local symbol, e.g.:
//// import {a} from "mod";
//// export {a as somethingElse}
//// We want the *local* declaration of 'a' as declared in the import,
//// *not* as declared within "mod" (or farther)
const aliasSymbol = getAliasSymbolForPropertyNameSymbol(symbol, location);
if (aliasSymbol) {
result = result.concat(populateSearchSymbolSet(aliasSymbol, location));
}
// If the location is in a context sensitive location (i.e. in an object literal) try
@ -6125,6 +6235,13 @@ namespace ts {
result = result.concat(typeChecker.getSymbolsOfParameterPropertyDeclaration(<ParameterDeclaration>symbol.valueDeclaration, symbol.name));
}
// If this is symbol of binding element without propertyName declaration in Object binding pattern
// Include the property in the search
const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(symbol);
if (bindingElementPropertySymbol) {
result.push(bindingElementPropertySymbol);
}
// 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
forEach(typeChecker.getRootSymbols(symbol), rootSymbol => {
@ -6206,32 +6323,40 @@ namespace ts {
}
// If the reference symbol is an alias, check if what it is aliasing is one of the search
// symbols.
if (isImportSpecifierSymbol(referenceSymbol)) {
const aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol);
if (searchSymbols.indexOf(aliasedSymbol) >= 0) {
return aliasedSymbol;
}
}
// For export specifiers, it can be a local symbol, e.g.
// import {a} from "mod";
// export {a as somethingElse}
// We want the local target of the export (i.e. the import symbol) and not the final target (i.e. "mod".a)
if (referenceLocation.parent.kind === SyntaxKind.ExportSpecifier) {
const aliasedSymbol = typeChecker.getExportSpecifierLocalTargetSymbol(<ExportSpecifier>referenceLocation.parent);
if (searchSymbols.indexOf(aliasedSymbol) >= 0) {
return aliasedSymbol;
}
// symbols but by looking up for related symbol of this alias so it can handle multiple level of indirectness.
const aliasSymbol = getAliasSymbolForPropertyNameSymbol(referenceSymbol, referenceLocation);
if (aliasSymbol) {
return getRelatedSymbol(searchSymbols, aliasSymbol, referenceLocation);
}
// 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
if (isNameOfPropertyAssignment(referenceLocation)) {
return forEach(getPropertySymbolsFromContextualType(referenceLocation), contextualSymbol => {
const contextualSymbol = forEach(getPropertySymbolsFromContextualType(referenceLocation), contextualSymbol => {
return forEach(typeChecker.getRootSymbols(contextualSymbol), s => searchSymbols.indexOf(s) >= 0 ? s : undefined);
});
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) { }
const propertySymbol = getPropertySymbolOfDestructuringAssignment(referenceLocation);
if (propertySymbol && searchSymbols.indexOf(propertySymbol) >= 0) {
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 };
const bindingElementPropertySymbol = getPropertySymbolOfObjectBindingPatternWithoutPropertyName(referenceSymbol);
if (bindingElementPropertySymbol && searchSymbols.indexOf(bindingElementPropertySymbol) >= 0) {
return bindingElementPropertySymbol;
}
// Unwrap symbols to get to the root (e.g. transient symbols as a result of widening)

View File

@ -19,7 +19,7 @@
let debugObjectHost = (<any>this);
// We need to use 'null' to interface with the managed side.
/* tslint:disable:no-null */
/* tslint:disable:no-null-keyword */
/* tslint:disable:no-in-operator */
/* @internal */
@ -67,6 +67,7 @@ namespace ts {
useCaseSensitiveFileNames?(): boolean;
getModuleResolutionsForFile?(fileName: string): string;
getTypeReferenceDirectiveResolutionsForFile?(fileName: string): string;
directoryExists(directoryName: string): boolean;
}
@ -281,6 +282,7 @@ namespace ts {
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[];
public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[];
public directoryExists: (directoryName: string) => boolean;
constructor(private shimHost: LanguageServiceShimHost) {
@ -298,6 +300,12 @@ namespace ts {
if ("directoryExists" in this.shimHost) {
this.directoryExists = directoryName => this.shimHost.directoryExists(directoryName);
}
if ("getTypeReferenceDirectiveResolutionsForFile" in this.shimHost) {
this.resolveTypeReferenceDirectives = (typeDirectiveNames: string[], containingFile: string) => {
const typeDirectivesForFile = <Map<ResolvedTypeReferenceDirective>>JSON.parse(this.shimHost.getTypeReferenceDirectiveResolutionsForFile(containingFile));
return map(typeDirectiveNames, name => lookUp(typeDirectivesForFile, name));
};
}
}
public log(s: string): void {
@ -919,38 +927,49 @@ namespace ts {
});
}
public resolveTypeReferenceDirective(fileName: string, typeReferenceDirective: string, compilerOptionsJson: string): string {
return this.forwardJSONCall(`resolveTypeReferenceDirective(${fileName})`, () => {
const compilerOptions = <CompilerOptions>JSON.parse(compilerOptionsJson);
const result = resolveTypeReferenceDirective(typeReferenceDirective, normalizeSlashes(fileName), compilerOptions, this.host);
return {
resolvedFileName: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.resolvedFileName : undefined,
primary: result.resolvedTypeReferenceDirective ? result.resolvedTypeReferenceDirective.primary : true,
failedLookupLocations: result.failedLookupLocations
};
});
}
public getPreProcessedFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
"getPreProcessedFileInfo('" + fileName + "')",
() => {
// for now treat files as JavaScript
const result = preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true);
const convertResult = {
referencedFiles: <IFileReference[]>[],
importedFiles: <IFileReference[]>[],
return {
referencedFiles: this.convertFileReferences(result.referencedFiles),
importedFiles: this.convertFileReferences(result.importedFiles),
ambientExternalModules: result.ambientExternalModules,
isLibFile: result.isLibFile
isLibFile: result.isLibFile,
typeReferenceDirectives: this.convertFileReferences(result.typeReferenceDirectives)
};
forEach(result.referencedFiles, refFile => {
convertResult.referencedFiles.push({
path: normalizePath(refFile.fileName),
position: refFile.pos,
length: refFile.end - refFile.pos
});
});
forEach(result.importedFiles, importedFile => {
convertResult.importedFiles.push({
path: normalizeSlashes(importedFile.fileName),
position: importedFile.pos,
length: importedFile.end - importedFile.pos
});
});
return convertResult;
});
}
private convertFileReferences(refs: FileReference[]): IFileReference[] {
if (!refs) {
return undefined;
}
const result: IFileReference[] = [];
for (const ref of refs) {
result.push({
path: normalizeSlashes(ref.fileName),
position: ref.pos,
length: ref.end - ref.pos
});
}
return result;
}
public getTSConfigFileInfo(fileName: string, sourceTextSnapshot: IScriptSnapshot): string {
return this.forwardJSONCall(
`getTSConfigFileInfo('${fileName}')`,

View File

@ -559,7 +559,7 @@ namespace ts.SignatureHelp {
signatureHelpParameters = typeParameters && typeParameters.length > 0 ? map(typeParameters, createSignatureHelpParameterForTypeParameter) : emptyArray;
suffixDisplayParts.push(punctuationPart(SyntaxKind.GreaterThanToken));
let parameterParts = mapToDisplayParts(writer =>
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.parameters, writer, invocation));
typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisType, candidateSignature.parameters, writer, invocation));
addRange(suffixDisplayParts, parameterParts);
}
else {

View File

@ -6,32 +6,6 @@ namespace ts {
list: Node;
}
export function getEndLinePosition(line: number, sourceFile: SourceFile): number {
Debug.assert(line >= 0);
let lineStarts = sourceFile.getLineStarts();
let lineIndex = line;
if (lineIndex + 1 === lineStarts.length) {
// last line - return EOF
return sourceFile.text.length - 1;
}
else {
// current line start
let start = lineStarts[lineIndex];
// take the start position of the next line -1 = it should be some line break
let pos = lineStarts[lineIndex + 1] - 1;
Debug.assert(isLineBreak(sourceFile.text.charCodeAt(pos)));
// walk backwards skipping line breaks, stop the the beginning of current line.
// i.e:
// <some text>
// $ <- end of line for this position should match the start position
while (start <= pos && isLineBreak(sourceFile.text.charCodeAt(pos))) {
pos--;
}
return pos;
}
}
export function getLineStartPositionForPosition(position: number, sourceFile: SourceFile): number {
let lineStarts = sourceFile.getLineStarts();
let line = sourceFile.getLineAndCharacterOfPosition(position).line;

View File

@ -56,8 +56,8 @@ var r3 = foo3(a); // any
declare function foo5(x: Date): Date;
>foo5 : Symbol(foo5, Decl(anyAssignabilityInInheritance.ts, 19, 17), Decl(anyAssignabilityInInheritance.ts, 21, 37))
>x : Symbol(x, Decl(anyAssignabilityInInheritance.ts, 21, 22))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
declare function foo5(x: any): any;
>foo5 : Symbol(foo5, Decl(anyAssignabilityInInheritance.ts, 19, 17), Decl(anyAssignabilityInInheritance.ts, 21, 37))

View File

@ -44,7 +44,7 @@ var d: boolean = a;
var e: Date = a;
>e : Symbol(e, Decl(anyAssignableToEveryType.ts, 17, 3))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(anyAssignableToEveryType.ts, 0, 3))
var f: any = a;
@ -109,12 +109,12 @@ var o: <T>(x: T) => T = a;
var p: Number = a;
>p : Symbol(p, Decl(anyAssignableToEveryType.ts, 31, 3))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(anyAssignableToEveryType.ts, 0, 3))
var q: String = a;
>q : Symbol(q, Decl(anyAssignableToEveryType.ts, 32, 3))
>String : Symbol(String, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>String : Symbol(String, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>a : Symbol(a, Decl(anyAssignableToEveryType.ts, 0, 3))
function foo<T, U /*extends T*/, V extends Date>(x: T, y: U, z: V) {
@ -122,7 +122,7 @@ function foo<T, U /*extends T*/, V extends Date>(x: T, y: U, z: V) {
>T : Symbol(T, Decl(anyAssignableToEveryType.ts, 34, 13))
>U : Symbol(U, Decl(anyAssignableToEveryType.ts, 34, 15))
>V : Symbol(V, Decl(anyAssignableToEveryType.ts, 34, 32))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>x : Symbol(x, Decl(anyAssignableToEveryType.ts, 34, 49))
>T : Symbol(T, Decl(anyAssignableToEveryType.ts, 34, 13))
>y : Symbol(y, Decl(anyAssignableToEveryType.ts, 34, 54))

View File

@ -50,7 +50,7 @@ interface I5 {
[x: string]: Date;
>x : Symbol(x, Decl(anyAssignableToEveryType2.ts, 27, 5))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
foo: any;
>foo : Symbol(I5.foo, Decl(anyAssignableToEveryType2.ts, 27, 22))

View File

@ -14,9 +14,9 @@ function doubleAndReturnAsArray(x: number, y: number, z: number): [number, numbe
>arguments : Symbol(arguments)
result.push(arg + arg);
>result.push : Symbol(Array.push, Decl(lib.d.ts, --, --))
>result.push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --))
>result : Symbol(result, Decl(argumentsObjectIterator01_ES6.ts, 2, 7))
>push : Symbol(Array.push, Decl(lib.d.ts, --, --))
>push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --))
>arg : Symbol(arg, Decl(argumentsObjectIterator01_ES6.ts, 3, 12))
>arg : Symbol(arg, Decl(argumentsObjectIterator01_ES6.ts, 3, 12))
}

View File

@ -9,9 +9,9 @@ function doubleAndReturnAsArray(x: number, y: number, z: number): [number, numbe
let blah = arguments[Symbol.iterator];
>blah : Symbol(blah, Decl(argumentsObjectIterator02_ES6.ts, 2, 7))
>arguments : Symbol(arguments)
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, --, --))
>Symbol : Symbol(Symbol, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.d.ts, --, --))
>Symbol.iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
>Symbol : Symbol(Symbol, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --))
>iterator : Symbol(SymbolConstructor.iterator, Decl(lib.es2015.symbol.wellknown.d.ts, --, --))
let result = [];
>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7))
@ -21,9 +21,9 @@ function doubleAndReturnAsArray(x: number, y: number, z: number): [number, numbe
>blah : Symbol(blah, Decl(argumentsObjectIterator02_ES6.ts, 2, 7))
result.push(arg + arg);
>result.push : Symbol(Array.push, Decl(lib.d.ts, --, --))
>result.push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --))
>result : Symbol(result, Decl(argumentsObjectIterator02_ES6.ts, 4, 7))
>push : Symbol(Array.push, Decl(lib.d.ts, --, --))
>push : Symbol(Array.push, Decl(lib.es5.d.ts, --, --))
>arg : Symbol(arg, Decl(argumentsObjectIterator02_ES6.ts, 5, 12))
>arg : Symbol(arg, Decl(argumentsObjectIterator02_ES6.ts, 5, 12))
}

View File

@ -1,5 +1,5 @@
tests/cases/compiler/arrayCast.ts(3,23): error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
tests/cases/compiler/arrayCast.ts(3,23): error TS2352: Type '{ foo: string; }[]' cannot be converted to type '{ id: number; }[]'.
Type '{ foo: string; }' is not comparable to type '{ id: number; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
@ -8,8 +8,8 @@ tests/cases/compiler/arrayCast.ts(3,23): error TS2352: Neither type '{ foo: stri
// has type { foo: string }[], which is not assignable to { id: number }[].
<{ id: number; }[]>[{ foo: "s" }];
~~~~~~~~
!!! error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
!!! error TS2352: Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
!!! error TS2352: Type '{ foo: string; }[]' cannot be converted to type '{ id: number; }[]'.
!!! error TS2352: Type '{ foo: string; }' is not comparable to type '{ id: number; }'.
!!! error TS2352: Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
// Should succeed, as the {} element causes the type of the array to be {}[]

View File

@ -81,13 +81,13 @@ var temp4 = [];
interface myArray extends Array<Number> { }
>myArray : Symbol(myArray, Decl(arrayLiterals2ES5.ts, 42, 15))
>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES5.ts, 44, 43))
>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>String : Symbol(String, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>String : Symbol(String, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
var d0 = [1, true, ...temp,]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES5.ts, 46, 3))

View File

@ -72,14 +72,14 @@ var temp2: [number[], string[]] = [[1, 2, 3], ["hello", "string"]];
interface myArray extends Array<Number> { }
>myArray : Symbol(myArray, Decl(arrayLiterals2ES6.ts, 40, 67))
>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
interface myArray2 extends Array<Number|String> { }
>myArray2 : Symbol(myArray2, Decl(arrayLiterals2ES6.ts, 42, 43))
>Array : Symbol(Array, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>String : Symbol(String, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --))
>Number : Symbol(Number, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --))
var d0 = [1, true, ...temp, ]; // has type (string|number|boolean)[]
>d0 : Symbol(d0, Decl(arrayLiterals2ES6.ts, 44, 3))

View File

@ -0,0 +1,111 @@
tests/cases/compiler/arrowFunctionErrorSpan.ts(4,3): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(7,3): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(12,3): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(17,3): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(18,5): error TS1200: Line terminator not permitted before arrow.
tests/cases/compiler/arrowFunctionErrorSpan.ts(21,3): error TS2345: Argument of type '(a: any, b: any, c: any, d: any) => void' is not assignable to parameter of type '() => number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(28,7): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(32,7): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(36,7): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(43,5): error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
Type 'void' is not assignable to type 'number'.
tests/cases/compiler/arrowFunctionErrorSpan.ts(52,3): error TS2345: Argument of type '(_: any) => number' is not assignable to parameter of type '() => number'.
==== tests/cases/compiler/arrowFunctionErrorSpan.ts (11 errors) ====
function f(a: () => number) { }
// oneliner
f(() => { });
~~~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
// multiline, body
f(() => {
~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
});
// multiline 2, body
f(() => {
~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
});
// multiline 3, arrow on a new line
f(()
~~
=> { });
~~~~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
~~
!!! error TS1200: Line terminator not permitted before arrow.
// multiline 4, arguments
f((a,
~~~
b,
~~~~~~
c,
~~~~~~
d) => { });
~~~~~~~~~~~~~
!!! error TS2345: Argument of type '(a: any, b: any, c: any, d: any) => void' is not assignable to parameter of type '() => number'.
// single line with a comment
f(/*
*/() => { });
~~~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
// multi line with a comment
f(/*
*/() => { });
~~~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
// multi line with a comment 2
f(/*
*/() => {
~~~~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
});
// multi line with a comment 3
f( // comment 1
// comment 2
() =>
~~~~~
!!! error TS2345: Argument of type '() => void' is not assignable to parameter of type '() => number'.
!!! error TS2345: Type 'void' is not assignable to type 'number'.
// comment 3
{
// comment 4
}
// comment 5
);
// body is not a block
f(_ => 1 +
~~~~~~~~
2);
~~~~~
!!! error TS2345: Argument of type '(_: any) => number' is not assignable to parameter of type '() => number'.

View File

@ -0,0 +1,89 @@
//// [arrowFunctionErrorSpan.ts]
function f(a: () => number) { }
// oneliner
f(() => { });
// multiline, body
f(() => {
});
// multiline 2, body
f(() => {
});
// multiline 3, arrow on a new line
f(()
=> { });
// multiline 4, arguments
f((a,
b,
c,
d) => { });
// single line with a comment
f(/*
*/() => { });
// multi line with a comment
f(/*
*/() => { });
// multi line with a comment 2
f(/*
*/() => {
});
// multi line with a comment 3
f( // comment 1
// comment 2
() =>
// comment 3
{
// comment 4
}
// comment 5
);
// body is not a block
f(_ => 1 +
2);
//// [arrowFunctionErrorSpan.js]
function f(a) { }
// oneliner
f(function () { });
// multiline, body
f(function () {
});
// multiline 2, body
f(function () {
});
// multiline 3, arrow on a new line
f(function () { });
// multiline 4, arguments
f(function (a, b, c, d) { });
// single line with a comment
f(/*
*/ function () { });
// multi line with a comment
f(/*
*/ function () { });
// multi line with a comment 2
f(/*
*/ function () {
});
// multi line with a comment 3
f(// comment 1
// comment 2
function () {
// comment 4
});
// body is not a block
f(function (_) { return 1 +
2; });

View File

@ -1,13 +1,13 @@
=== tests/cases/compiler/arrowFunctionWithObjectLiteralBody6.ts ===
var a = () => <Error>{ name: "foo", message: "bar" };
>a : Symbol(a, Decl(arrowFunctionWithObjectLiteralBody6.ts, 0, 3))
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>name : Symbol(name, Decl(arrowFunctionWithObjectLiteralBody6.ts, 0, 22))
>message : Symbol(message, Decl(arrowFunctionWithObjectLiteralBody6.ts, 0, 35))
var b = () => (<Error>{ name: "foo", message: "bar" });
>b : Symbol(b, Decl(arrowFunctionWithObjectLiteralBody6.ts, 2, 3))
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>name : Symbol(name, Decl(arrowFunctionWithObjectLiteralBody6.ts, 2, 23))
>message : Symbol(message, Decl(arrowFunctionWithObjectLiteralBody6.ts, 2, 36))
@ -18,7 +18,7 @@ var c = () => ({ name: "foo", message: "bar" });
var d = () => ((<Error>({ name: "foo", message: "bar" })));
>d : Symbol(d, Decl(arrowFunctionWithObjectLiteralBody6.ts, 6, 3))
>Error : Symbol(Error, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --))
>name : Symbol(name, Decl(arrowFunctionWithObjectLiteralBody6.ts, 6, 25))
>message : Symbol(message, Decl(arrowFunctionWithObjectLiteralBody6.ts, 6, 38))

View File

@ -13,7 +13,7 @@ var y = (null as string).length;
var z = Date as any as string;
>z : Symbol(z, Decl(asOperator1.ts, 3, 3))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;

View File

@ -1,8 +1,8 @@
tests/cases/conformance/expressions/asOperator/asOperator2.ts(1,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
tests/cases/conformance/expressions/asOperator/asOperator2.ts(1,9): error TS2352: Type 'number' cannot be converted to type 'string'.
==== tests/cases/conformance/expressions/asOperator/asOperator2.ts (1 errors) ====
var x = 23 as string;
~~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
!!! error TS2352: Type 'number' cannot be converted to type 'string'.

View File

@ -1,10 +1,10 @@
tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts(2,9): error TS2352: Neither type '(v: number) => number' nor type '(x: number) => string' is assignable to the other.
Type 'number' is not assignable to type 'string'.
tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts(2,9): error TS2352: Type '(v: number) => number' cannot be converted to type '(x: number) => string'.
Type 'number' is not comparable to type 'string'.
==== tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts (1 errors) ====
// should error
var x = (v => v) as (x: number) => string;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2352: Neither type '(v: number) => number' nor type '(x: number) => string' is assignable to the other.
!!! error TS2352: Type 'number' is not assignable to type 'string'.
!!! error TS2352: Type '(v: number) => number' cannot be converted to type '(x: number) => string'.
!!! error TS2352: Type 'number' is not comparable to type 'string'.

View File

@ -1,11 +1,11 @@
tests/cases/conformance/expressions/asOperator/asOperatorNames.ts(2,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
tests/cases/conformance/expressions/asOperator/asOperatorNames.ts(2,9): error TS2352: Type 'number' cannot be converted to type 'string'.
==== tests/cases/conformance/expressions/asOperator/asOperatorNames.ts (1 errors) ====
var a = 20;
var b = a as string;
~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
!!! error TS2352: Type 'number' cannot be converted to type 'string'.
var as = "hello";
var as1 = as as string;

View File

@ -189,8 +189,8 @@ var a18: {
(a: Date): Date;
>a : Symbol(a, Decl(assignmentCompatWithCallSignatures3.ts, 40, 9))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}): any[];
}

View File

@ -189,8 +189,8 @@ var a18: {
new (a: Date): Date;
>a : Symbol(a, Decl(assignmentCompatWithConstructSignatures3.ts, 40, 13))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Date : Symbol(Date, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
}): any[];
}

View File

@ -5,7 +5,7 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(8,5): error TS2322: Type '
Property 'apply' is missing in type '{}'.
tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type 'typeof bad' is not assignable to type 'Function'.
Types of property 'apply' are incompatible.
Type 'number' is not assignable to type '(thisArg: any, argArray?: any) => any'.
Type 'number' is not assignable to type '{ <T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U; (this: Function, thisArg: any, argArray?: any): any; }'.
==== tests/cases/compiler/assignmentToObjectAndFunction.ts (3 errors) ====
@ -48,4 +48,4 @@ tests/cases/compiler/assignmentToObjectAndFunction.ts(29,5): error TS2322: Type
~~~~~~~~~~
!!! error TS2322: Type 'typeof bad' is not assignable to type 'Function'.
!!! error TS2322: Types of property 'apply' are incompatible.
!!! error TS2322: Type 'number' is not assignable to type '(thisArg: any, argArray?: any) => any'.
!!! error TS2322: Type 'number' is not assignable to type '{ <T, U>(this: (this: T, ...argArray: any[]) => U, thisArg: T, argArray?: any): U; (this: Function, thisArg: any, argArray?: any): any; }'.

View File

@ -2,7 +2,7 @@
type PromiseAlias<T> = Promise<T>;
>PromiseAlias : Symbol(PromiseAlias, Decl(asyncAliasReturnType_es6.ts, 0, 0))
>T : Symbol(T, Decl(asyncAliasReturnType_es6.ts, 0, 18))
>Promise : Symbol(Promise, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --))
>T : Symbol(T, Decl(asyncAliasReturnType_es6.ts, 0, 18))
async function f(): PromiseAlias<void> {

View File

@ -2,6 +2,6 @@
var foo = async (): Promise<void> => {
>foo : Symbol(foo, Decl(asyncArrowFunction1_es6.ts, 1, 3))
>Promise : Symbol(Promise, Decl(lib.d.ts, --, --), Decl(lib.d.ts, --, --))
>Promise : Symbol(Promise, Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --))
};

Some files were not shown because too many files have changed in this diff Show More