From 08f9659a3b4a2d2cad90cc50639279ec1372fcb5 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 17:45:45 +0200 Subject: [PATCH 001/154] clean: remove glMatrix definition (it is only used internally) and add space after every colon --- gl-matrix/gl-matrix-typed-tests.ts | 3 +- gl-matrix/gl-matrix-typed.d.ts | 296 ++++++++++++++--------------- 2 files changed, 144 insertions(+), 155 deletions(-) diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts index 7364ec0a83..361690b5e7 100644 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -1,8 +1,7 @@ /// // common -import {vec2, mat2, mat3, mat4, vec3, vec4, glMatrix, mat2d, quat} from "./gl-matrix-typed"; -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix-typed"; var outVal: number; var outBool: boolean; diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index e172074fec..1309e994c8 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -3,16 +3,6 @@ // Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Common -export class glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - public static toRadian(a: number): number; -} - // vec2 export class vec2 extends Float32Array { private typeVec2:number; @@ -137,7 +127,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to ceil * @returns {vec2} out */ - public static ceil(out:vec2, a:vec2):vec2; + public static ceil(out: vec2, a: vec2): vec2; /** * Math.floor the components of a vec2 @@ -146,7 +136,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to floor * @returns {vec2} out */ - public static floor (out:vec2, a:vec2):vec2; + public static floor (out: vec2, a: vec2): vec2; /** * Returns the minimum of two vec2's @@ -175,7 +165,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to round * @returns {vec2} out */ - public static round(out:vec2, a:vec2):vec2; + public static round(out: vec2, a: vec2): vec2; /** @@ -427,7 +417,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec2, b:vec2): boolean; + public static exactEquals (a: vec2, b: vec2): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -436,7 +426,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec2, b:vec2) : boolean; + public static equals (a: vec2, b: vec2) : boolean; } // vec3 @@ -565,7 +555,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to ceil * @returns {vec3} out */ - public static ceil (out:vec3, a:vec3) : vec3; + public static ceil (out: vec3, a: vec3) : vec3; /** * Math.floor the components of a vec3 @@ -574,7 +564,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to floor * @returns {vec3} out */ - public static floor (out:vec3, a:vec3) :vec3; + public static floor (out: vec3, a: vec3) : vec3; /** * Returns the minimum of two vec3's @@ -603,7 +593,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to round * @returns {vec3} out */ - public static round (out:vec3, a:vec3) : vec3 + public static round (out: vec3, a: vec3) : vec3 /** * Scales a vec3 by a scalar number @@ -762,7 +752,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static hermite (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) : vec3; + public static hermite (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; /** * Performs a bezier interpolation with two control points @@ -775,7 +765,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static bezier (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) :vec3; + public static bezier (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; /** * Generates a random unit vector @@ -908,7 +898,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec3, b:vec3): boolean + public static exactEquals (a: vec3, b: vec3): boolean /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -917,7 +907,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec3, b:vec3) : boolean + public static equals (a: vec3, b: vec3) : boolean } // vec4 @@ -1048,7 +1038,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to ceil * @returns {vec4} out */ - public static ceil (out:vec4, a:vec4) : vec4; + public static ceil (out: vec4, a: vec4) : vec4; /** * Math.floor the components of a vec4 @@ -1057,7 +1047,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to floor * @returns {vec4} out */ - public static floor (out:vec4, a:vec4) : vec4; + public static floor (out: vec4, a: vec4) : vec4; /** * Returns the minimum of two vec4's @@ -1086,7 +1076,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to round * @returns {vec4} out */ - public static round (out:vec4, a:vec4): vec4; + public static round (out: vec4, a: vec4): vec4; /** * Scales a vec4 by a scalar number @@ -1306,7 +1296,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec4, b:vec4) : boolean; + public static exactEquals (a: vec4, b: vec4) : boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -1315,7 +1305,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec4, b:vec4) : boolean; + public static equals (a: vec4, b: vec4) : boolean; } // mat2 @@ -1327,7 +1317,7 @@ export class mat2 extends Float32Array { * * @returns a new 2x2 matrix */ - public static create():mat2; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1335,7 +1325,7 @@ export class mat2 extends Float32Array { * @param a matrix to clone * @returns a new 2x2 matrix */ - public static clone(a:mat2):mat2; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1344,7 +1334,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat2, a:mat2):mat2; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1352,7 +1342,7 @@ export class mat2 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat2):mat2; + public static identity(out: mat2): mat2; /** * Create a new mat2 with the given values @@ -1363,7 +1353,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out A new 2x2 matrix */ - public static fromValues(m00:number, m01:number, m10:number, m11:number):mat2; + public static fromValues(m00:number, m01:number, m10:number, m11:number): mat2; /** * Set the components of a mat2 to the given values @@ -1375,7 +1365,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out */ - public static set(out:mat2, m00:number, m01:number, m10:number, m11:number):mat2; + public static set(out: mat2, m00:number, m01:number, m10:number, m11:number): mat2; /** * Transpose the values of a mat2 @@ -1384,7 +1374,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat2, a:mat2):mat2; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1393,7 +1383,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat2, a:mat2):mat2; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1402,7 +1392,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat2, a:mat2):mat2; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1410,7 +1400,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat2):number; + public static determinant(a: mat2):number; /** * Multiplies two mat2's @@ -1420,7 +1410,7 @@ export class mat2 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat2, a:mat2, b:mat2):mat2; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1430,7 +1420,7 @@ export class mat2 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat2, a:mat2, b:mat2):mat2; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1440,7 +1430,7 @@ export class mat2 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out:mat2, a:mat2, rad:number):mat2; + public static rotate(out: mat2, a: mat2, rad:number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1450,7 +1440,7 @@ export class mat2 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out:mat2, a:mat2, v:vec2):mat2; + public static scale(out: mat2, a: mat2, v: vec2): mat2; /** * Creates a matrix from a given angle @@ -1463,7 +1453,7 @@ export class mat2 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2} out */ - public static fromRotation(out:mat2, rad:number):mat2; + public static fromRotation(out: mat2, rad:number): mat2; /** * Creates a matrix from a vector scaling @@ -1476,7 +1466,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out:mat2, v:vec2):mat2; + public static fromScaling(out: mat2, v: vec2): mat2; /** * Returns a string representation of a mat2 @@ -1484,7 +1474,7 @@ export class mat2 extends Float32Array { * @param a matrix to represent as a string * @returns string representation of the matrix */ - public static str(a:mat2):string; + public static str(a: mat2):string; /** * Returns Frobenius norm of a mat2 @@ -1492,7 +1482,7 @@ export class mat2 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat2):number; + public static frob(a: mat2):number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1501,7 +1491,7 @@ export class mat2 extends Float32Array { * @param U the upper triangular matrix * @param a the input matrix to factorize */ - public static LDU(L:mat2, D:mat2, U:mat2, a:mat2):mat2; + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; /** * Adds two mat2's @@ -1511,7 +1501,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static add(out:mat2, a:mat2, b:mat2):mat2; + public static add(out: mat2, a: mat2, b: mat2): mat2; /** * Subtracts matrix b from matrix a @@ -1521,7 +1511,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static subtract (out:mat2, a:mat2, b:mat2):mat2; + public static subtract (out: mat2, a: mat2, b: mat2): mat2; /** * Subtracts matrix b from matrix a @@ -1531,7 +1521,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static sub (out:mat2, a:mat2, b:mat2):mat2; + public static sub (out: mat2, a: mat2, b: mat2): mat2; /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -1540,7 +1530,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a:mat2, b:mat2):boolean; + public static exactEquals (a: mat2, b: mat2):boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -1549,7 +1539,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a:mat2, b:mat2) :boolean; + public static equals (a: mat2, b: mat2) :boolean; /** * Multiply each element of the matrix by a scalar. @@ -1559,7 +1549,7 @@ export class mat2 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2} out */ - public static multiplyScalar (out:mat2, a:mat2, b:number) :mat2 + public static multiplyScalar (out: mat2, a: mat2, b:number) : mat2 /** * Adds two mat2's after multiplying each element of the second operand by a scalar value. @@ -1570,7 +1560,7 @@ export class mat2 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat2} out */ - public static multiplyScalarAndAdd (out:mat2, a:mat2, b:mat2, scale:number): mat2 + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale:number): mat2 @@ -1638,7 +1628,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} out */ - public static set (out:mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) :mat2d + public static set (out: mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d /** * Inverts a mat2d @@ -1718,7 +1708,7 @@ export class mat2d extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2d} out */ - public static fromRotation (out:mat2d, rad:number): mat2d; + public static fromRotation (out: mat2d, rad:number): mat2d; /** * Creates a matrix from a vector scaling @@ -1731,7 +1721,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2d} out */ - public static fromScaling (out:mat2d, v:vec2):mat2d; + public static fromScaling (out: mat2d, v: vec2): mat2d; /** * Creates a matrix from a vector translation @@ -1744,7 +1734,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Translation vector * @returns {mat2d} out */ - public static fromTranslation (out:mat2d, v:vec2):mat2d + public static fromTranslation (out: mat2d, v: vec2): mat2d /** * Returns a string representation of a mat2d @@ -1841,7 +1831,7 @@ export class mat3 extends Float32Array { * * @returns a new 3x3 matrix */ - public static create():mat3; + public static create(): mat3; /** * Copies the upper-left 3x3 values into the given mat3. @@ -1850,7 +1840,7 @@ export class mat3 extends Float32Array { * @param {mat4} a the source 4x4 matrix * @returns {mat3} out */ - public static fromMat4(out:mat3, a:mat4):mat3 + public static fromMat4(out: mat3, a: mat4): mat3 /** * Creates a new mat3 initialized with values from an existing matrix @@ -1858,7 +1848,7 @@ export class mat3 extends Float32Array { * @param a matrix to clone * @returns a new 3x3 matrix */ - public static clone(a:mat3):mat3; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1867,7 +1857,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat3, a:mat3):mat3; + public static copy(out: mat3, a: mat3): mat3; /** * Create a new mat3 with the given values @@ -1883,7 +1873,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} A new mat3 */ - public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3; + public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3; /** @@ -1901,7 +1891,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} out */ - public static set(out:mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3 + public static set(out: mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3 /** * Set a mat3 to the identity matrix @@ -1909,7 +1899,7 @@ export class mat3 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat3):mat3; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1918,7 +1908,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat3, a:mat3):mat3; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1927,7 +1917,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat3, a:mat3):mat3; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1936,7 +1926,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat3, a:mat3):mat3; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1944,7 +1934,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat3):number; + public static determinant(a: mat3):number; /** * Multiplies two mat3's @@ -1954,7 +1944,7 @@ export class mat3 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat3, a:mat3, b:mat3):mat3; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1964,7 +1954,7 @@ export class mat3 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat3, a:mat3, b:mat3):mat3; + public static mul(out: mat3, a: mat3, b: mat3): mat3; /** @@ -1975,7 +1965,7 @@ export class mat3 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out:mat3, a:mat3, v:vec3):mat3; + public static translate(out: mat3, a: mat3, v: vec3): mat3; /** * Rotates a mat3 by the given angle @@ -1985,7 +1975,7 @@ export class mat3 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out:mat3, a:mat3, rad:number):mat3; + public static rotate(out: mat3, a: mat3, rad:number): mat3; /** * Scales the mat3 by the dimensions in the given vec2 @@ -1995,7 +1985,7 @@ export class mat3 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out:mat3, a:mat3, v:vec2):mat3; + public static scale(out: mat3, a: mat3, v: vec2): mat3; /** * Creates a matrix from a vector translation @@ -2008,7 +1998,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Translation vector * @returns {mat3} out */ - public static fromTranslation(out:mat3, v:vec2):mat3 + public static fromTranslation(out: mat3, v: vec2): mat3 /** * Creates a matrix from a given angle @@ -2021,7 +2011,7 @@ export class mat3 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat3} out */ - public static fromRotation(out:mat3, rad:number):mat3 + public static fromRotation(out: mat3, rad:number): mat3 /** * Creates a matrix from a vector scaling @@ -2034,7 +2024,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat3} out */ - public static fromScaling(out:mat3, v:vec2):mat3 + public static fromScaling(out: mat3, v: vec2): mat3 /** * Copies the values from a mat2d into a mat3 @@ -2043,7 +2033,7 @@ export class mat3 extends Float32Array { * @param {mat2d} a the matrix to copy * @returns out **/ - public static fromMat2d(out:mat3, a:mat2d):mat3; + public static fromMat2d(out: mat3, a: mat2d): mat3; /** * Calculates a 3x3 matrix from the given quaternion @@ -2053,7 +2043,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static fromQuat(out:mat3, q:quat):mat3; + public static fromQuat(out: mat3, q: quat): mat3; /** * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix @@ -2063,7 +2053,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static normalFromMat4(out:mat3, a:mat4):mat3; + public static normalFromMat4(out: mat3, a: mat4): mat3; /** * Returns a string representation of a mat3 @@ -2071,7 +2061,7 @@ export class mat3 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat:mat3):string; + public static str(mat: mat3):string; /** * Returns Frobenius norm of a mat3 @@ -2079,7 +2069,7 @@ export class mat3 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat3):number; + public static frob(a: mat3):number; /** * Adds two mat3's @@ -2089,7 +2079,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static add(out:mat3, a:mat3, b:mat3):mat3 + public static add(out: mat3, a: mat3, b: mat3): mat3 /** * Subtracts matrix b from matrix a @@ -2099,7 +2089,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static subtract(out:mat3, a:mat3, b:mat3):mat3 + public static subtract(out: mat3, a: mat3, b: mat3): mat3 /** * Subtracts matrix b from matrix a @@ -2109,7 +2099,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static sub(out:mat3, a:mat3, b:mat3):mat3 + public static sub(out: mat3, a: mat3, b: mat3): mat3 /** * Multiply each element of the matrix by a scalar. @@ -2119,7 +2109,7 @@ export class mat3 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat3} out */ - public static multiplyScalar(out:mat3, a:mat3, b:number):mat3 + public static multiplyScalar(out: mat3, a: mat3, b:number): mat3 /** * Adds two mat3's after multiplying each element of the second operand by a scalar value. @@ -2130,7 +2120,7 @@ export class mat3 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat3} out */ - public static multiplyScalarAndAdd(out:mat3, a:mat3, b:mat3, scale:number):mat3 + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale:number): mat3 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2139,7 +2129,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals(a:mat3, b:mat3):boolean; + public static exactEquals(a: mat3, b: mat3):boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2148,7 +2138,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals(a:mat3, b:mat3):boolean + public static equals(a: mat3, b: mat3):boolean } // mat4 @@ -2160,7 +2150,7 @@ export class mat4 extends Float32Array { * * @returns a new 4x4 matrix */ - public static create():mat4; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -2168,7 +2158,7 @@ export class mat4 extends Float32Array { * @param a matrix to clone * @returns a new 4x4 matrix */ - public static clone(a:mat4):mat4; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -2177,7 +2167,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat4, a:mat4):mat4; + public static copy(out: mat4, a: mat4): mat4; /** @@ -2201,7 +2191,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} A new mat4 */ - public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; + public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; /** * Set the components of a mat4 to the given values @@ -2225,7 +2215,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} out */ - public static set(out:mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; + public static set(out: mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; /** * Set a mat4 to the identity matrix @@ -2233,7 +2223,7 @@ export class mat4 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat4):mat4; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -2242,7 +2232,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat4, a:mat4):mat4; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -2251,7 +2241,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat4, a:mat4):mat4; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -2260,7 +2250,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat4, a:mat4):mat4; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -2268,7 +2258,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat4):number; + public static determinant(a: mat4):number; /** * Multiplies two mat4's @@ -2278,7 +2268,7 @@ export class mat4 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat4, a:mat4, b:mat4):mat4; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -2288,7 +2278,7 @@ export class mat4 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat4, a:mat4, b:mat4):mat4; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -2298,7 +2288,7 @@ export class mat4 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out:mat4, a:mat4, v:vec3):mat4; + public static translate(out: mat4, a: mat4, v: vec3): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -2308,7 +2298,7 @@ export class mat4 extends Float32Array { * @param v the vec3 to scale the matrix by * @returns out **/ - public static scale(out:mat4, a:mat4, v:vec3):mat4; + public static scale(out: mat4, a: mat4, v: vec3): mat4; /** * Rotates a mat4 by the given angle @@ -2319,7 +2309,7 @@ export class mat4 extends Float32Array { * @param axis the axis to rotate around * @returns out */ - public static rotate(out:mat4, a:mat4, rad:number, axis:vec3):mat4; + public static rotate(out: mat4, a: mat4, rad:number, axis: vec3): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -2329,7 +2319,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateX(out:mat4, a:mat4, rad:number):mat4; + public static rotateX(out: mat4, a: mat4, rad:number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -2339,7 +2329,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateY(out:mat4, a:mat4, rad:number):mat4; + public static rotateY(out: mat4, a: mat4, rad:number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -2349,7 +2339,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateZ(out:mat4, a:mat4, rad:number):mat4; + public static rotateZ(out: mat4, a: mat4, rad:number): mat4; /** * Creates a matrix from a vector translation @@ -2362,7 +2352,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Translation vector * @returns {mat4} out */ - public static fromTranslation(out:mat4, v:vec3):mat4 + public static fromTranslation(out: mat4, v: vec3): mat4 /** * Creates a matrix from a vector scaling @@ -2375,7 +2365,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Scaling vector * @returns {mat4} out */ - public static fromScaling(out:mat4, v:vec3):mat4 + public static fromScaling(out: mat4, v: vec3): mat4 /** * Creates a matrix from a given angle around a given axis @@ -2389,7 +2379,7 @@ export class mat4 extends Float32Array { * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ - public static fromRotation(out:mat4, rad:number, axis:vec3):mat4 + public static fromRotation(out: mat4, rad:number, axis: vec3): mat4 /** * Creates a matrix from the given angle around the X axis @@ -2402,7 +2392,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromXRotation(out:mat4, rad:number):mat4 + public static fromXRotation(out: mat4, rad:number): mat4 /** * Creates a matrix from the given angle around the Y axis @@ -2415,7 +2405,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromYRotation(out:mat4, rad:number):mat4 + public static fromYRotation(out: mat4, rad:number): mat4 /** @@ -2429,7 +2419,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromZRotation(out:mat4, rad:number):mat4 + public static fromZRotation(out: mat4, rad:number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -2446,7 +2436,7 @@ export class mat4 extends Float32Array { * @param v Translation vector * @returns out */ - public static fromRotationTranslation(out:mat4, q:quat, v:vec3):mat4; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3): mat4; /** * Returns the translation vector component of a transformation @@ -2457,7 +2447,7 @@ export class mat4 extends Float32Array { * @param {mat4} mat Matrix to be decomposed (input) * @return {vec3} out */ - public static getTranslation(out:vec3, mat:mat4):vec3; + public static getTranslation(out: vec3, mat: mat4): vec3; /** * Returns a quaternion representing the rotational component @@ -2468,7 +2458,7 @@ export class mat4 extends Float32Array { * @param {mat4} mat Matrix to be decomposed (input) * @return {quat} out */ - public static getRotation(out:quat, mat:mat4):quat; + public static getRotation(out: quat, mat: mat4): quat; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale @@ -2487,7 +2477,7 @@ export class mat4 extends Float32Array { * @param s Scaling vector * @returns out */ - public static fromRotationTranslationScale(out:mat4, q:quat, v:vec3, s:vec3):mat4; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3, s: vec3): mat4; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin @@ -2509,7 +2499,7 @@ export class mat4 extends Float32Array { * @param {vec3} o The origin vector around which to scale and rotate * @returns {mat4} out */ - public static fromRotationTranslationScaleOrigin(out:mat4, q:quat, v:vec3, s:vec3, o:vec3):mat4 + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3, s: vec3, o: vec3): mat4 /** * Calculates a 4x4 matrix from the given quaternion @@ -2519,7 +2509,7 @@ export class mat4 extends Float32Array { * * @returns {mat4} out */ - public static fromQuat(out:mat4, q:quat):mat4 + public static fromQuat(out: mat4, q: quat): mat4 /** * Generates a frustum matrix with the given bounds @@ -2533,8 +2523,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static frustum(out:mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number):mat4; + public static frustum(out: mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number): mat4; /** * Generates a perspective projection matrix with the given bounds @@ -2546,8 +2536,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static perspective(out:mat4, fovy:number, aspect:number, - near:number, far:number):mat4; + public static perspective(out: mat4, fovy:number, aspect:number, + near:number, far:number): mat4; /** * Generates a perspective projection matrix with the given field of view. @@ -2560,9 +2550,9 @@ export class mat4 extends Float32Array { * @param {number} far Far bound of the frustum * @returns {mat4} out */ - public static perspectiveFromFieldOfView(out:mat4, + public static perspectiveFromFieldOfView(out: mat4, fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near:number, far:number):mat4 + near:number, far:number): mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2576,8 +2566,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static ortho(out:mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number):mat4; + public static ortho(out: mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number): mat4; /** * Generates a look-at matrix with the given eye position, focal point, and up axis @@ -2588,7 +2578,7 @@ export class mat4 extends Float32Array { * @param up vec3 pointing up * @returns out */ - public static lookAt(out:mat4, eye:vec3, center:vec3, up:vec3):mat4; + public static lookAt(out: mat4, eye: vec3, center: vec3, up: vec3): mat4; /** * Returns a string representation of a mat4 @@ -2596,7 +2586,7 @@ export class mat4 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat:mat4):string; + public static str(mat: mat4):string; /** * Returns Frobenius norm of a mat4 @@ -2604,7 +2594,7 @@ export class mat4 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat4):number; + public static frob(a: mat4):number; /** * Adds two mat4's @@ -2614,7 +2604,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static add(out:mat4, a:mat4, b:mat4):mat4 + public static add(out: mat4, a: mat4, b: mat4): mat4 /** * Subtracts matrix b from matrix a @@ -2624,7 +2614,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static subtract(out:mat4, a:mat4, b:mat4):mat4 + public static subtract(out: mat4, a: mat4, b: mat4): mat4 /** * Subtracts matrix b from matrix a @@ -2634,7 +2624,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static sub(out:mat4, a:mat4, b:mat4):mat4 + public static sub(out: mat4, a: mat4, b: mat4): mat4 /** * Multiply each element of the matrix by a scalar. @@ -2644,7 +2634,7 @@ export class mat4 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat4} out */ - public static multiplyScalar(out:mat4, a:mat4, b:number):mat4 + public static multiplyScalar(out: mat4, a: mat4, b:number): mat4 /** * Adds two mat4's after multiplying each element of the second operand by a scalar value. @@ -2655,7 +2645,7 @@ export class mat4 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat4} out */ - public static multiplyScalarAndAdd (out:mat4, a:mat4, b:mat4, scale:number):mat4 + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale:number): mat4 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2664,7 +2654,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a:mat4, b:mat4) :boolean + public static exactEquals (a: mat4, b: mat4) :boolean /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2673,7 +2663,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a:mat4, b:mat4): boolean + public static equals (a: mat4, b: mat4): boolean } @@ -2740,6 +2730,18 @@ export class quat extends Float32Array { */ public static identity(out: quat): quat; + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3, right: vec3, up: vec3): quat + /** * Sets a quaternion to represent the shortest rotation from one * vector to another. @@ -2751,19 +2753,7 @@ export class quat extends Float32Array { * @param {vec3} b the destination vector * @returns {quat} out */ - public static rotationTo (out:quat, a:vec3, b:vec3): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out:quat, view:vec3, right:vec3, up:vec3):quat + public static rotationTo (out: quat, a: vec3, b: vec3): quat; @@ -2791,7 +2781,7 @@ export class quat extends Float32Array { * @param {quat} q Quaternion to be decomposed * @return {number} Angle, in radians, of the rotation */ - public static getAxisAngle (out_axis:vec3, q:quat) :number + public static getAxisAngle (out_axis: vec3, q: quat) :number /** * Adds two quat's @@ -2912,7 +2902,7 @@ export class quat extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static slerp(out:quat, a:quat, b:quat, t:number): quat; + public static slerp(out: quat, a: quat, b: quat, t:number): quat; /** * Performs a spherical linear interpolation with two control points @@ -3041,7 +3031,7 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static exactEquals (a:quat, b:quat) : boolean; + public static exactEquals (a: quat, b: quat) : boolean; /** * Returns whether or not the quaternions have approximately the same elements in the same position. @@ -3050,5 +3040,5 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static equals (a:quat, b:quat) : boolean; + public static equals (a: quat, b: quat) : boolean; } From 568c64aa047cf20d2ff4a7e2128ccfa7bf326483 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 17:47:26 +0200 Subject: [PATCH 002/154] feature: add option of number array input for all vector arguments --- gl-matrix/gl-matrix-typed-tests.ts | 4 +- gl-matrix/gl-matrix-typed.d.ts | 430 ++++++++++++++--------------- 2 files changed, 218 insertions(+), 216 deletions(-) diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts index 361690b5e7..64f6beb7a4 100644 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -79,6 +79,7 @@ vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); outStr = vec2.str(vec2A); outBool = vec2.exactEquals(vec2A, vec2B); outBool = vec2.equals(vec2A, vec2B); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 outVec3 = vec3.create(); @@ -129,6 +130,7 @@ outVal = vec3.angle(vec3A, vec3B); outStr = vec3.str(vec3A); outBool = vec3.exactEquals(vec3A, vec3B); outBool = vec3.equals(vec3A, vec3B); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 outVec4 = vec4.create(); @@ -170,6 +172,7 @@ vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); outStr = vec4.str(vec4A); outBool = vec4.exactEquals(vec4A, vec4B); outBool = vec4.equals(vec4A, vec4B); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 outMat2 = mat2.create(); @@ -229,7 +232,6 @@ outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); outBool = mat2d.exactEquals(mat2dA, mat2dB); outBool = mat2d.equals(mat2dA, mat2dB); - // mat3 outMat3 = mat3.create(); outMat3 = mat3.fromMat4(outMat3, mat4A); diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index 1309e994c8..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -5,7 +5,7 @@ // vec2 export class vec2 extends Float32Array { - private typeVec2:number; + private typeVec2: number; /** * Creates a new, empty vec2 @@ -20,7 +20,7 @@ export class vec2 extends Float32Array { * @param a a vector to clone * @returns a new 2D vector */ - public static clone(a: vec2): vec2; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -38,7 +38,7 @@ export class vec2 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec2, a: vec2): vec2; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -58,7 +58,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec2, a: vec2, b: vec2): vec2; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -68,7 +68,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec2, a: vec2, b: vec2): vec2; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -78,7 +78,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec2, a: vec2, b: vec2): vec2; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -88,7 +88,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec2, a: vec2, b: vec2): vec2; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -98,7 +98,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec2, a: vec2, b: vec2): vec2; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -108,7 +108,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec2, a: vec2, b: vec2): vec2; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -118,7 +118,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec2, a: vec2, b: vec2): vec2; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Math.ceil the components of a vec2 @@ -127,7 +127,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to ceil * @returns {vec2} out */ - public static ceil(out: vec2, a: vec2): vec2; + public static ceil(out: vec2, a: vec2 | number[]): vec2; /** * Math.floor the components of a vec2 @@ -136,7 +136,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to floor * @returns {vec2} out */ - public static floor (out: vec2, a: vec2): vec2; + public static floor (out: vec2, a: vec2 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec2, a: vec2, b: vec2): vec2; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec2, a: vec2, b: vec2): vec2; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Math.round the components of a vec2 @@ -165,7 +165,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to round * @returns {vec2} out */ - public static round(out: vec2, a: vec2): vec2; + public static round(out: vec2, a: vec2 | number[]): vec2; /** @@ -176,7 +176,7 @@ export class vec2 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec2, a: vec2, b: number): vec2; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -187,7 +187,7 @@ export class vec2 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec2, a: vec2, b: vec2, scale: number): vec2; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -196,7 +196,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec2, b: vec2): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -205,7 +205,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec2, b: vec2): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -214,7 +214,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec2, b: vec2): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -223,7 +223,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec2, b: vec2): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -231,7 +231,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec2): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -239,7 +239,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec2): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -247,7 +247,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec2): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -255,7 +255,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec2): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -264,7 +264,7 @@ export class vec2 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec2, a: vec2): vec2; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -273,7 +273,7 @@ export class vec2 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec2, a: vec2): vec2; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -282,7 +282,7 @@ export class vec2 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec2, a: vec2): vec2; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -291,7 +291,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec2, b: vec2): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -302,7 +302,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static cross(out: vec2, a: vec2, b: vec2): vec2; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -313,7 +313,7 @@ export class vec2 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec2, a: vec2, b: vec2, t: number): vec2; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -340,7 +340,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat2(out: vec2, a: vec2, m: mat2): vec2; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -350,7 +350,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat2d(out: vec2, a: vec2, m: mat2d): vec2; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -361,7 +361,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat3(out: vec2, a: vec2, m: mat3): vec2; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -373,7 +373,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec2, a: vec2, m: mat4): vec2; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -387,7 +387,7 @@ export class vec2 extends Float32Array { * @returns a */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2, arg: any) => void, arg: any): Float32Array; + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -400,7 +400,7 @@ export class vec2 extends Float32Array { * @returns a */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2) => void): Float32Array; + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector @@ -408,7 +408,7 @@ export class vec2 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec2): string; + public static str(a: vec2 | number[]): string; /** * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) @@ -417,7 +417,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec2, b: vec2): boolean; + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -426,12 +426,12 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec2, b: vec2) : boolean; + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; } // vec3 export class vec3 extends Float32Array { - private typeVec3:number; + private typeVec3: number; /** * Creates a new, empty vec3 @@ -446,7 +446,7 @@ export class vec3 extends Float32Array { * @param a vector to clone * @returns a new 3D vector */ - public static clone(a: vec3): vec3; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -465,7 +465,7 @@ export class vec3 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec3, a: vec3): vec3; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -486,7 +486,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec3, a: vec3, b: vec3): vec3; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -496,7 +496,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec3, a: vec3, b: vec3): vec3; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -506,7 +506,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec3, a: vec3, b: vec3): vec3 + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -516,7 +516,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec3, a: vec3, b: vec3): vec3; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -526,7 +526,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec3, a: vec3, b: vec3): vec3; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -536,7 +536,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec3, a: vec3, b: vec3): vec3; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -546,7 +546,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec3, a: vec3, b: vec3): vec3; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Math.ceil the components of a vec3 @@ -555,7 +555,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to ceil * @returns {vec3} out */ - public static ceil (out: vec3, a: vec3) : vec3; + public static ceil (out: vec3, a: vec3 | number[]): vec3; /** * Math.floor the components of a vec3 @@ -564,7 +564,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to floor * @returns {vec3} out */ - public static floor (out: vec3, a: vec3) : vec3; + public static floor (out: vec3, a: vec3 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -574,7 +574,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec3, a: vec3, b: vec3): vec3; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -584,7 +584,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec3, a: vec3, b: vec3): vec3; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Math.round the components of a vec3 @@ -593,7 +593,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to round * @returns {vec3} out */ - public static round (out: vec3, a: vec3) : vec3 + public static round (out: vec3, a: vec3 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -603,7 +603,7 @@ export class vec3 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec3, a: vec3, b: number): vec3; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -614,7 +614,7 @@ export class vec3 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec3, a: vec3, b: vec3, scale: number): vec3; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -623,7 +623,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec3, b: vec3): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -632,7 +632,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec3, b: vec3): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -641,7 +641,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec3, b: vec3): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -650,7 +650,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec3, b: vec3): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -658,7 +658,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec3): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -666,7 +666,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec3): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -674,7 +674,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec3): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -682,7 +682,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec3): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -691,7 +691,7 @@ export class vec3 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec3, a: vec3): vec3; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -700,7 +700,7 @@ export class vec3 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec3, a: vec3): vec3; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -709,7 +709,7 @@ export class vec3 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec3, a: vec3): vec3; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -718,7 +718,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec3, b: vec3): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -728,7 +728,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static cross(out: vec3, a: vec3, b: vec3): vec3; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -739,7 +739,7 @@ export class vec3 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec3, a: vec3, b: vec3, t: number): vec3; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; /** * Performs a hermite interpolation with two control points @@ -752,7 +752,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static hermite (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Performs a bezier interpolation with two control points @@ -765,7 +765,7 @@ export class vec3 extends Float32Array { * @param {number} t interpolation amount between the two inputs * @returns {vec3} out */ - public static bezier (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -792,7 +792,7 @@ export class vec3 extends Float32Array { * @param m the 3x3 matrix to transform with * @returns out */ - public static transformMat3(out: vec3, a: vec3, m: mat3): vec3; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -803,7 +803,7 @@ export class vec3 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec3, a: vec3, m: mat4): vec3; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; /** * Transforms the vec3 with a quat @@ -813,7 +813,7 @@ export class vec3 extends Float32Array { * @param q quaternion to transform with * @returns out */ - public static transformQuat(out: vec3, a: vec3, q: quat): vec3; + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; /** @@ -824,7 +824,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateX(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Rotate a 3D vector around the y-axis @@ -834,7 +834,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateY(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Rotate a 3D vector around the z-axis @@ -844,7 +844,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateZ(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Perform some operation over an array of vec3s. @@ -859,7 +859,7 @@ export class vec3 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3, arg: any) => void, arg: any): Float32Array; + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -873,7 +873,7 @@ export class vec3 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3) => void): Float32Array; + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -881,7 +881,7 @@ export class vec3 extends Float32Array { * @param b The second operand * @returns The angle in radians */ - public static angle(a: vec3, b: vec3): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector @@ -889,7 +889,7 @@ export class vec3 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec3): string; + public static str(a: vec3 | number[]): string; /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) @@ -898,7 +898,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec3, b: vec3): boolean + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -907,12 +907,12 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec3, b: vec3) : boolean + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean } // vec4 export class vec4 extends Float32Array { - private typeVec3:number; + private typeVec3: number; /** * Creates a new, empty vec4 @@ -927,7 +927,7 @@ export class vec4 extends Float32Array { * @param a vector to clone * @returns a new 4D vector */ - public static clone(a: vec4): vec4; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -947,7 +947,7 @@ export class vec4 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec4, a: vec4): vec4; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -969,7 +969,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec4, a: vec4, b: vec4): vec4; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -979,7 +979,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec4, a: vec4, b: vec4): vec4; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -989,7 +989,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec4, a: vec4, b: vec4): vec4; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -999,7 +999,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec4, a: vec4, b: vec4): vec4; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -1009,7 +1009,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec4, a: vec4, b: vec4): vec4; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -1019,7 +1019,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec4, a: vec4, b: vec4): vec4; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -1029,7 +1029,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec4, a: vec4, b: vec4): vec4; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Math.ceil the components of a vec4 @@ -1038,7 +1038,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to ceil * @returns {vec4} out */ - public static ceil (out: vec4, a: vec4) : vec4; + public static ceil (out: vec4, a: vec4 | number[]): vec4; /** * Math.floor the components of a vec4 @@ -1047,7 +1047,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to floor * @returns {vec4} out */ - public static floor (out: vec4, a: vec4) : vec4; + public static floor (out: vec4, a: vec4 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -1057,7 +1057,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec4, a: vec4, b: vec4): vec4; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -1067,7 +1067,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec4, a: vec4, b: vec4): vec4; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Math.round the components of a vec4 @@ -1076,7 +1076,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to round * @returns {vec4} out */ - public static round (out: vec4, a: vec4): vec4; + public static round (out: vec4, a: vec4 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -1086,7 +1086,7 @@ export class vec4 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec4, a: vec4, b: number): vec4; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -1097,7 +1097,7 @@ export class vec4 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec4, a: vec4, b: vec4, scale: number): vec4; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -1106,7 +1106,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec4, b: vec4): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -1115,7 +1115,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec4, b: vec4): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1124,7 +1124,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec4, b: vec4): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1133,7 +1133,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec4, b: vec4): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1141,7 +1141,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec4): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1149,7 +1149,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec4): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1157,7 +1157,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec4): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1165,7 +1165,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec4): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1174,7 +1174,7 @@ export class vec4 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec4, a: vec4): vec4; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1183,7 +1183,7 @@ export class vec4 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec4, a: vec4): vec4; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1192,7 +1192,7 @@ export class vec4 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec4, a: vec4): vec4; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1201,7 +1201,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec4, b: vec4): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1212,7 +1212,7 @@ export class vec4 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec4, a: vec4, b: vec4, t: number): vec4; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1239,7 +1239,7 @@ export class vec4 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec4, a: vec4, m: mat4): vec4; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1250,7 +1250,7 @@ export class vec4 extends Float32Array { * @returns out */ - public static transformQuat(out: vec4, a: vec4, q: quat): vec4; + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1265,7 +1265,7 @@ export class vec4 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4, arg: any) => void, arg: any): Float32Array; + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1279,7 +1279,7 @@ export class vec4 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4) => void): Float32Array; + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector @@ -1287,7 +1287,7 @@ export class vec4 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec4): string; + public static str(a: vec4 | number[]): string; /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) @@ -1296,7 +1296,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec4, b: vec4) : boolean; + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -1305,12 +1305,12 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec4, b: vec4) : boolean; + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; } // mat2 export class mat2 extends Float32Array { - private typeMat2:number; + private typeMat2: number; /** * Creates a new identity mat2 @@ -1353,7 +1353,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out A new 2x2 matrix */ - public static fromValues(m00:number, m01:number, m10:number, m11:number): mat2; + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; /** * Set the components of a mat2 to the given values @@ -1365,7 +1365,7 @@ export class mat2 extends Float32Array { * @param {number} m11 Component in column 1, row 1 position (index 3) * @returns {mat2} out */ - public static set(out: mat2, m00:number, m01:number, m10:number, m11:number): mat2; + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; /** * Transpose the values of a mat2 @@ -1400,7 +1400,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat2):number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1430,7 +1430,7 @@ export class mat2 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out: mat2, a: mat2, rad:number): mat2; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1440,7 +1440,7 @@ export class mat2 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat2, a: mat2, v: vec2): mat2; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; /** * Creates a matrix from a given angle @@ -1453,7 +1453,7 @@ export class mat2 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2} out */ - public static fromRotation(out: mat2, rad:number): mat2; + public static fromRotation(out: mat2, rad: number): mat2; /** * Creates a matrix from a vector scaling @@ -1466,7 +1466,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out: mat2, v: vec2): mat2; + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1474,7 +1474,7 @@ export class mat2 extends Float32Array { * @param a matrix to represent as a string * @returns string representation of the matrix */ - public static str(a: mat2):string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1482,7 +1482,7 @@ export class mat2 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat2):number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1530,7 +1530,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a: mat2, b: mat2):boolean; + public static exactEquals (a: mat2, b: mat2): boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -1539,7 +1539,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a: mat2, b: mat2) :boolean; + public static equals (a: mat2, b: mat2): boolean; /** * Multiply each element of the matrix by a scalar. @@ -1549,7 +1549,7 @@ export class mat2 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2} out */ - public static multiplyScalar (out: mat2, a: mat2, b:number) : mat2 + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 /** * Adds two mat2's after multiplying each element of the second operand by a scalar value. @@ -1560,7 +1560,7 @@ export class mat2 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat2} out */ - public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale:number): mat2 + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 @@ -1568,7 +1568,7 @@ export class mat2 extends Float32Array { // mat2d export class mat2d extends Float32Array { - private typeMat2d:number; + private typeMat2d: number; /** * Creates a new identity mat2d @@ -1613,7 +1613,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} A new mat2d */ - public static fromValues (a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** @@ -1628,7 +1628,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} out */ - public static set (out: mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** * Inverts a mat2d @@ -1685,7 +1685,7 @@ export class mat2d extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat2d, a: mat2d, v: vec2): mat2d; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1695,7 +1695,7 @@ export class mat2d extends Float32Array { * @param v the vec2 to translate the matrix by * @returns out **/ - public static translate(out: mat2d, a: mat2d, v: vec2): mat2d; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Creates a matrix from a given angle @@ -1708,7 +1708,7 @@ export class mat2d extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2d} out */ - public static fromRotation (out: mat2d, rad:number): mat2d; + public static fromRotation (out: mat2d, rad: number): mat2d; /** * Creates a matrix from a vector scaling @@ -1721,7 +1721,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2d} out */ - public static fromScaling (out: mat2d, v: vec2): mat2d; + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; /** * Creates a matrix from a vector translation @@ -1734,7 +1734,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Translation vector * @returns {mat2d} out */ - public static fromTranslation (out: mat2d, v: vec2): mat2d + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1801,7 +1801,7 @@ export class mat2d extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat2d} out */ - public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale:number) : mat2d + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -1824,7 +1824,7 @@ export class mat2d extends Float32Array { // mat3 export class mat3 extends Float32Array { - private typeMat3:number; + private typeMat3: number; /** * Creates a new identity mat3 @@ -1873,7 +1873,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} A new mat3 */ - public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3; + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; /** @@ -1891,7 +1891,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} out */ - public static set(out: mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3 + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 /** * Set a mat3 to the identity matrix @@ -1934,7 +1934,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat3):number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1965,7 +1965,7 @@ export class mat3 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out: mat3, a: mat3, v: vec3): mat3; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1975,7 +1975,7 @@ export class mat3 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out: mat3, a: mat3, rad:number): mat3; + public static rotate(out: mat3, a: mat3, rad: number): mat3; /** * Scales the mat3 by the dimensions in the given vec2 @@ -1985,7 +1985,7 @@ export class mat3 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat3, a: mat3, v: vec2): mat3; + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; /** * Creates a matrix from a vector translation @@ -1998,7 +1998,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Translation vector * @returns {mat3} out */ - public static fromTranslation(out: mat3, v: vec2): mat3 + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 /** * Creates a matrix from a given angle @@ -2011,7 +2011,7 @@ export class mat3 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat3} out */ - public static fromRotation(out: mat3, rad:number): mat3 + public static fromRotation(out: mat3, rad: number): mat3 /** * Creates a matrix from a vector scaling @@ -2024,7 +2024,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat3} out */ - public static fromScaling(out: mat3, v: vec2): mat3 + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 /** * Copies the values from a mat2d into a mat3 @@ -2061,7 +2061,7 @@ export class mat3 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat: mat3):string; + public static str(mat: mat3): string; /** * Returns Frobenius norm of a mat3 @@ -2069,7 +2069,7 @@ export class mat3 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat3):number; + public static frob(a: mat3): number; /** * Adds two mat3's @@ -2109,7 +2109,7 @@ export class mat3 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat3} out */ - public static multiplyScalar(out: mat3, a: mat3, b:number): mat3 + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 /** * Adds two mat3's after multiplying each element of the second operand by a scalar value. @@ -2120,7 +2120,7 @@ export class mat3 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat3} out */ - public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale:number): mat3 + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2129,7 +2129,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals(a: mat3, b: mat3):boolean; + public static exactEquals(a: mat3, b: mat3): boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2138,12 +2138,12 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals(a: mat3, b: mat3):boolean + public static equals(a: mat3, b: mat3): boolean } // mat4 export class mat4 extends Float32Array { - private typeMat4:number; + private typeMat4: number; /** * Creates a new identity mat4 @@ -2191,7 +2191,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} A new mat4 */ - public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set the components of a mat4 to the given values @@ -2215,7 +2215,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} out */ - public static set(out: mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number): mat4; + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set a mat4 to the identity matrix @@ -2258,7 +2258,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat4):number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -2288,7 +2288,7 @@ export class mat4 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out: mat4, a: mat4, v: vec3): mat4; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -2298,7 +2298,7 @@ export class mat4 extends Float32Array { * @param v the vec3 to scale the matrix by * @returns out **/ - public static scale(out: mat4, a: mat4, v: vec3): mat4; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -2309,7 +2309,7 @@ export class mat4 extends Float32Array { * @param axis the axis to rotate around * @returns out */ - public static rotate(out: mat4, a: mat4, rad:number, axis: vec3): mat4; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -2319,7 +2319,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateX(out: mat4, a: mat4, rad:number): mat4; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -2329,7 +2329,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateY(out: mat4, a: mat4, rad:number): mat4; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -2339,7 +2339,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateZ(out: mat4, a: mat4, rad:number): mat4; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** * Creates a matrix from a vector translation @@ -2352,7 +2352,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Translation vector * @returns {mat4} out */ - public static fromTranslation(out: mat4, v: vec3): mat4 + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** * Creates a matrix from a vector scaling @@ -2365,7 +2365,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Scaling vector * @returns {mat4} out */ - public static fromScaling(out: mat4, v: vec3): mat4 + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** * Creates a matrix from a given angle around a given axis @@ -2379,7 +2379,7 @@ export class mat4 extends Float32Array { * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ - public static fromRotation(out: mat4, rad:number, axis: vec3): mat4 + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** * Creates a matrix from the given angle around the X axis @@ -2392,7 +2392,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromXRotation(out: mat4, rad:number): mat4 + public static fromXRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from the given angle around the Y axis @@ -2405,7 +2405,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromYRotation(out: mat4, rad:number): mat4 + public static fromYRotation(out: mat4, rad: number): mat4 /** @@ -2419,7 +2419,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromZRotation(out: mat4, rad:number): mat4 + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -2436,7 +2436,7 @@ export class mat4 extends Float32Array { * @param v Translation vector * @returns out */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3): mat4; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** * Returns the translation vector component of a transformation @@ -2477,7 +2477,7 @@ export class mat4 extends Float32Array { * @param s Scaling vector * @returns out */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3, s: vec3): mat4; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin @@ -2499,7 +2499,7 @@ export class mat4 extends Float32Array { * @param {vec3} o The origin vector around which to scale and rotate * @returns {mat4} out */ - public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3, s: vec3, o: vec3): mat4 + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 /** * Calculates a 4x4 matrix from the given quaternion @@ -2523,8 +2523,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static frustum(out: mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number): mat4; + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; /** * Generates a perspective projection matrix with the given bounds @@ -2536,8 +2536,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static perspective(out: mat4, fovy:number, aspect:number, - near:number, far:number): mat4; + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; /** * Generates a perspective projection matrix with the given field of view. @@ -2551,8 +2551,8 @@ export class mat4 extends Float32Array { * @returns {mat4} out */ public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near:number, far:number): mat4 + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2566,8 +2566,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static ortho(out: mat4, left:number, right:number, - bottom:number, top:number, near:number, far:number): mat4; + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; /** * Generates a look-at matrix with the given eye position, focal point, and up axis @@ -2578,7 +2578,7 @@ export class mat4 extends Float32Array { * @param up vec3 pointing up * @returns out */ - public static lookAt(out: mat4, eye: vec3, center: vec3, up: vec3): mat4; + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; /** * Returns a string representation of a mat4 @@ -2586,7 +2586,7 @@ export class mat4 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat: mat4):string; + public static str(mat: mat4): string; /** * Returns Frobenius norm of a mat4 @@ -2594,7 +2594,7 @@ export class mat4 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat4):number; + public static frob(a: mat4): number; /** * Adds two mat4's @@ -2634,7 +2634,7 @@ export class mat4 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat4} out */ - public static multiplyScalar(out: mat4, a: mat4, b:number): mat4 + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 /** * Adds two mat4's after multiplying each element of the second operand by a scalar value. @@ -2645,7 +2645,7 @@ export class mat4 extends Float32Array { * @param {number} scale the amount to scale b's elements by before adding * @returns {mat4} out */ - public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale:number): mat4 + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) @@ -2654,7 +2654,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a: mat4, b: mat4) :boolean + public static exactEquals (a: mat4, b: mat4): boolean /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2669,7 +2669,7 @@ export class mat4 extends Float32Array { // quat export class quat extends Float32Array { - private typeQuat:number; + private typeQuat: number; /** * Creates a new identity quat @@ -2730,18 +2730,6 @@ export class quat extends Float32Array { */ public static identity(out: quat): quat; - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out: quat, view: vec3, right: vec3, up: vec3): quat - /** * Sets a quaternion to represent the shortest rotation from one * vector to another. @@ -2753,7 +2741,19 @@ export class quat extends Float32Array { * @param {vec3} b the destination vector * @returns {quat} out */ - public static rotationTo (out: quat, a: vec3, b: vec3): quat; + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat @@ -2766,7 +2766,7 @@ export class quat extends Float32Array { * @param rad the angle in radians * @returns out **/ - public static setAxisAngle(out: quat, axis: vec3, rad: number): quat; + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; /** * Gets the rotation axis and angle for a given @@ -2781,7 +2781,7 @@ export class quat extends Float32Array { * @param {quat} q Quaternion to be decomposed * @return {number} Angle, in radians, of the rotation */ - public static getAxisAngle (out_axis: vec3, q: quat) :number + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number /** * Adds two quat's @@ -2902,7 +2902,7 @@ export class quat extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static slerp(out: quat, a: quat, b: quat, t:number): quat; + public static slerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation with two control points @@ -2998,7 +2998,7 @@ export class quat extends Float32Array { * @param up the vector representing the local "up" direction * @returns out */ - public static setAxes(out: quat, view: vec3, right: vec3, up: vec3): quat; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -3011,7 +3011,7 @@ export class quat extends Float32Array { * @param b the destination vector * @returns out */ - public static rotationTo(out: quat, a: vec3, b: vec3): quat; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -3031,7 +3031,7 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static exactEquals (a: quat, b: quat) : boolean; + public static exactEquals (a: quat, b: quat): boolean; /** * Returns whether or not the quaternions have approximately the same elements in the same position. @@ -3040,5 +3040,5 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static equals (a: quat, b: quat) : boolean; + public static equals (a: quat, b: quat): boolean; } From 3fbffb91e3837db19fa35ee4617317f9ed3e9370 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 18:13:26 +0200 Subject: [PATCH 003/154] rename old implementation to legacy and new to standard --- gl-matrix/gl-matrix-legacy-tests.ts | 362 ++++ gl-matrix/gl-matrix-legacy.d.ts | 2163 +++++++++++++++++++ gl-matrix/gl-matrix-tests.ts | 653 +++--- gl-matrix/gl-matrix-typed-tests.ts | 347 --- gl-matrix/gl-matrix-typed.d.ts | 3044 --------------------------- gl-matrix/gl-matrix.d.ts | 1697 +++++++++++---- 6 files changed, 4133 insertions(+), 4133 deletions(-) create mode 100644 gl-matrix/gl-matrix-legacy-tests.ts create mode 100644 gl-matrix/gl-matrix-legacy.d.ts delete mode 100644 gl-matrix/gl-matrix-typed-tests.ts delete mode 100644 gl-matrix/gl-matrix-typed.d.ts diff --git a/gl-matrix/gl-matrix-legacy-tests.ts b/gl-matrix/gl-matrix-legacy-tests.ts new file mode 100644 index 0000000000..5cfa9a1c3a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy-tests.ts @@ -0,0 +1,362 @@ +/// + +// common +var result: number = glMatrix.toRadian(180); + +var out: GLM.IArray; +var outVal: number; +var outStr: string; + +// vec2 +var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; +var vecArray: GLM.IArray; + +vecA = [1, 2]; +vecB = new Float32Array([3, 4]); +out = [0, 0]; +matA = [1, 2, 3, 4, 5, 6]; +vecArray = [1, 2, 3, 4, 0, 0]; + +out = vec2.create(); +out = vec2.clone(vecA); +out = vec2.fromValues(1, 2); +out = vec2.copy(out, vecA); +out = vec2.set(out, 1, 2); +out = vec2.add(out, vecA, vecB); +out = vec2.subtract(out, vecA, vecB); +out = vec2.sub(out, vecA, vecB); +out = vec2.multiply(out, vecA, vecB); +out = vec2.mul(out, vecA, vecB); +out = vec2.divide(out, vecA, vecB); +out = vec2.div(out, vecA, vecB); +out = vec2.min(out, vecA, vecB); +out = vec2.max(out, vecA, vecB); +out = vec2.scale(out, vecA, 2); +out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec2.distance(vecA, vecB); +outVal = vec2.dist(vecA, vecB); +outVal = vec2.squaredDistance(vecA, vecB); +outVal = vec2.sqrDist(vecA, vecB); +outVal = vec2.length(vecA); +outVal = vec2.len(vecA); +outVal = vec2.squaredLength(vecA); +outVal = vec2.sqrLen(vecA); +out = vec2.negate(out, vecA); +out = vec2.inverse(out, vecA); +out = vec2.normalize(out, vecA); +outVal = vec2.dot(vecA, vecB); +out = vec2.cross(out, vecA, vecB); +out = vec2.lerp(out, vecA, vecB, 0.5); +out = vec2.random(out); +out = vec2.random(out, 5.0); +out = vec2.transformMat2(out, vecA, matA); +out = vec2.transformMat2d(out, vecA, matA); +out = vec2.transformMat3(out, vecA, matA); +out = vec2.transformMat4(out, vecA, matA); +out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vecA); + +// vec3 +var matr: GLM.IArray; +var q: GLM.IArray; + +vecA = [1, 2, 3]; +vecB = new Float32Array([4, 5, 6]); +out = [0, 0, 0]; +vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; +matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + +out = vec3.create(); +out = vec3.clone(vecA); +out = vec3.fromValues(1, 2, 3); +out = vec3.copy(out, vecA); +out = vec3.set(out, 1, 2, 3); +out = vec3.add(out, vecA, vecB); +out = vec3.subtract(out, vecA, vecB); +out = vec3.sub(out, vecA, vecB); +out = vec3.multiply(out, vecA, vecB); +out = vec3.mul(out, vecA, vecB); +out = vec3.divide(out, vecA, vecB); +out = vec3.div(out, vecA, vecB); +out = vec3.min(out, vecA, vecB); +out = vec3.max(out, vecA, vecB); +out = vec3.scale(out, vecA, 2); +out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec3.distance(vecA, vecB); +outVal = vec3.dist(vecA, vecB); +outVal = vec3.squaredDistance(vecA, vecB); +outVal = vec3.sqrDist(vecA, vecB); +outVal = vec3.length(vecA); +outVal = vec3.len(vecA); +outVal = vec3.squaredLength(vecA); +outVal = vec3.sqrLen(vecA); +out = vec3.negate(out, vecA); +out = vec3.inverse(out, vecA); +out = vec3.normalize(out, vecA); +outVal = vec3.dot(vecA, vecB); +out = vec3.cross(out, vecA, vecB); +out = vec3.lerp(out, vecA, vecB, 0.5); +out = vec3.random(out); +out = vec3.random(out, 5.0); +out = vec3.rotateX(out, vecA, vecB, Math.PI); +out = vec3.rotateY(out, vecA, vecB, Math.PI); +out = vec3.rotateZ(out, vecA, vecB, Math.PI); +out = vec3.transformMat3(out, vecA, matr); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; +out = vec3.transformMat4(out, vecA, matr); + +q = [1, 2, 3, 4]; +out = vec3.transformQuat(out, vecA, matr); + +out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vecA, vecB); +outStr = vec3.str(vecA); + +// vec4 +var q: GLM.IArray; + +vecA = [1, 2, 3, 4]; +vecB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +q = [1, 2, 3, 4]; + +out = vec4.create(); +out = vec4.clone(vecA); +out = vec4.fromValues(1, 2, 3, 4); +out = vec4.copy(out, vecA); +out = vec4.set(out, 1, 2, 3, 4); +out = vec4.add(out, vecA, vecB); +out = vec4.subtract(out, vecA, vecB); +out = vec4.sub(out, vecA, vecB); +out = vec4.multiply(out, vecA, vecB); +out = vec4.mul(out, vecA, vecB); +out = vec4.divide(out, vecA, vecB); +out = vec4.div(out, vecA, vecB); +out = vec4.min(out, vecA, vecB); +out = vec4.max(out, vecA, vecB); +out = vec4.scale(out, vecA, 2); +out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec4.distance(vecA, vecB); +outVal = vec4.dist(vecA, vecB); +outVal = vec4.squaredDistance(vecA, vecB); +outVal = vec4.sqrDist(vecA, vecB); +outVal = vec4.length(vecA); +outVal = vec4.len(vecA); +outVal = vec4.squaredLength(vecA); +outVal = vec4.sqrLen(vecA); +out = vec4.negate(out, vecA); +out = vec4.inverse(out, vecA); +out = vec4.normalize(out, vecA); +outVal = vec4.dot(vecA, vecB); +out = vec4.lerp(out, vecA, vecB, 0.5); +out = vec4.random(out); +out = vec4.random(out, 5.0); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] +out = vec4.transformMat4(out, vecA, matr); +out = vec4.transformQuat(out, vecA, q); + +vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; +out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vecA); + +// mat2 +var matB: GLM.IArray, identity: GLM.IArray; + +matA = [1, 2, 3, 4]; +matB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +identity = [1, 0, 0, 1]; + +out = mat2.create(); +out = mat2.clone(matA); +out = mat2.copy(out, matA); +out = mat2.identity(out); +out = mat2.transpose(out, matA); +out = mat2.invert(out, matA); +out = mat2.adjoint(out, matA); +outVal = mat2.determinant(matA); +out = mat2.multiply(out, matA, matB); +out = mat2.mul(out, matA, matB); +out = mat2.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2.scale(out, matA, vecA); +outStr = mat2.str(matA); +outVal = mat2.frob(matA); + +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +out = mat2.LDU(L, D, U, [4,3,6,3]); + +// mat2d +matA = [1, 2, 3, 4, 5, 6]; +matB = [7, 8, 9, 10, 11, 12]; +out = [0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 1, 0, 0]; + +out = mat2d.create(); +out = mat2d.clone(matA); +out = mat2d.copy(out, matA); +out = mat2d.identity(out); +out = mat2d.invert(out, matA); +outVal = mat2d.determinant(matA); +out = mat2d.multiply(out, matA, matB); +out = mat2d.mul(out, matA, matB); +out = mat2d.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2d.scale(out, matA, vecA); +out = mat2d.translate(out, matA, vecA); +outStr = mat2d.str(matA); +outVal = mat2d.frob(matA); + +// mat3 +matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; +matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; +out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +out = mat3.create(); +out = mat3.clone(matA); +out = mat3.copy(out, matA); +out = mat3.identity(out); +out = mat3.transpose(out, matA); +out = mat3.invert(out, matA); +out = mat3.adjoint(out, matA); +outVal = mat3.determinant(matA); +out = mat3.multiply(out, matA, matB); +out = mat3.mul(out, matA, matB); +outStr = mat3.str(matA); +outVal = mat3.frob(matA); + +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; +out = mat3.normalFromMat4(out, matA); + +q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; +out = mat3.fromQuat(out, q); + +out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.scale(out, matA, [2,2]); +out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); + +out = mat3.translate(out, matA, [1, 2, 3]); +out = mat3.rotate(out, matA, Math.PI/2); + +// mat4 +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 1, 2, 3, 1]; + +matB = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 4, 5, 6, 1]; + +out = [0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0]; + +identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; + +out = mat4.create(); +out = mat4.clone(matA); +out = mat4.copy(out, matA); +out = mat4.identity(out); +out = mat4.transpose(out, matA); +out = mat4.invert(out, matA); +out = mat4.adjoint(out, matA); +outVal = mat4.determinant(matA); +out = mat4.multiply(out, matA, matB); +out = mat4.mul(out, matA, matB); +out = mat4.translate(out, matA, [4, 5, 6]); +out = mat4.scale(out, matA, [4, 5, 6]); + +var rad = Math.PI * 0.5; +var axis = [1, 0, 0]; +out = mat4.rotate(out, matA, rad, axis); +out = mat4.rotateX(out, matA, rad); +out = mat4.rotateY(out, matA, rad); +out = mat4.rotateZ(out, matA, rad); + +out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); + +var fovy = Math.PI * 0.5; +out = mat4.perspective(out, fovy, 1, 0, 1); +out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); + +var eye = [0, 0, 1]; +var center = [0, 0, -1]; +var up = [0, 1, 0]; +out = mat4.lookAt(out, eye, center, up); + +outStr = mat4.str(matA); +outVal = mat4.frob(matA); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); +out = mat4.fromQuat(out, q); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); +out = mat4.fromQuat(out, q); + + +// quat +var quatA = [1, 2, 3, 4]; +var quatB = [5, 6, 7, 8]; +out = [0, 0, 0, 0]; +var vec = [1, 1, -1]; +var id = [0, 0, 0, 1]; +var deg90 = Math.PI / 2; + +out = quat.create(); +out = quat.clone(quatA); +out = quat.fromValues(1, 2, 3, 4); +out = quat.copy(out, quatA); +out = quat.set(out, 1, 2, 3, 4); +out = quat.identity(out); +out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); +out = quat.add(out, quatA, quatB); +out = quat.multiply(out, quatA, quatB); +out = quat.mul(out, quatA, quatB); +out = quat.scale(out, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +out = quat.normalize(out, quatA); +outVal = quat.dot(out, quatA, quatB); +out = quat.lerp(out, quatA, quatB, 0.5); +out = quat.slerp(out, quatA, quatB, 0.5); +out = quat.invert(out, quatA); +out = quat.conjugate(out, quatA); +outStr = quat.str(quatA); +out = quat.rotateX(out, id, deg90); +out = quat.rotateY(out, id, deg90); +out = quat.rotateZ(out, id, deg90); + +matr = [ 1, 0, 0, + 0, 0, -1, + 0, 1, 0 ]; +out = quat.fromMat3(out, matr); + +var view = [-1, 0, 0]; +up = [ 0, 1, 0]; +var right= [ 0, 0,-1]; +out = quat.setAxes([], view, right, up); + +out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); +out = quat.calculateW(out, quatA); + diff --git a/gl-matrix/gl-matrix-legacy.d.ts b/gl-matrix/gl-matrix-legacy.d.ts new file mode 100644 index 0000000000..16366f263a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy.d.ts @@ -0,0 +1,2163 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Tat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace GLM { + interface IArray + { + /** + * Must be indexable like an array + */ + [index: number]: number; + } +} + +// Common +declare namespace glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + export function toRadian(a: number): number; +} + +// vec2 +declare namespace vec2 { + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + export function fromValues(x: number, y: number): GLM.IArray; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec3 +declare namespace vec3 { + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + export function fromValues(x: number, y: number, z: number): GLM.IArray; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + export function angle(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec4 +declare namespace vec4 { + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function dist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + export function dot(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// mat2 +declare namespace mat2 { + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; +} + +// mat2d +declare namespace mat2d { + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; +} + +// mat3 +declare namespace mat3 { + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param out the receiving 3x3 matrix + * @param a the source 4x4 matrix + * @returns out + */ + export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; +} + +// mat4 +declare namespace mat4 { + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(a: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function frustum(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function perspective(out: GLM.IArray, fovy: number, aspect: number, + near: number, far: number): GLM.IArray; + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + export function ortho(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + export function lookAt(out: GLM.IArray, eye: GLM.IArray, + center: GLM.IArray, up: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale. + * + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scale vector + * @returns out + */ + export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + + /** + * Creates a matrix from a quaternion + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; +} + +// quat +declare namespace quat { + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + export function create(): GLM.IArray; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a quatenion + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, + up: GLM.IArray): GLM.IArray; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; +} diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index 682bca7b8b..984ca3d1c3 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -1,362 +1,347 @@ /// // common -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix"; -var out: GLM.IArray; var outVal: number; +var outBool: boolean; var outStr: string; +let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +let vec2A = vec2.fromValues(1, 2); +let vec2B = vec2.fromValues(3, 4); +let vec3A = vec3.fromValues(1, 2, 3); +let vec3B = vec3.fromValues(3, 4, 5); +let vec4A = vec4.fromValues(1, 2, 3, 4); +let vec4B = vec4.fromValues(3, 4, 5, 6); +let mat2A = mat2.fromValues(1, 2, 3, 4); +let mat2B = mat2.fromValues(1, 2, 3, 4); +let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let quatA = quat.fromValues(1, 2, 3, 4); +let quatB = quat.fromValues(5, 6, 7, 8); + +let outVec2 = vec2.create(); +let outVec3 = vec3.create(); +let outVec4 = vec4.create(); +let outMat2 = mat2.create(); +let outMat2d = mat2d.create(); +let outMat3 = mat3.create(); +let outMat4 = mat4.create(); +let outQuat = quat.create(); + // vec2 -var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; -var vecArray: GLM.IArray; - -vecA = [1, 2]; -vecB = new Float32Array([3, 4]); -out = [0, 0]; -matA = [1, 2, 3, 4, 5, 6]; -vecArray = [1, 2, 3, 4, 0, 0]; - -out = vec2.create(); -out = vec2.clone(vecA); -out = vec2.fromValues(1, 2); -out = vec2.copy(out, vecA); -out = vec2.set(out, 1, 2); -out = vec2.add(out, vecA, vecB); -out = vec2.subtract(out, vecA, vecB); -out = vec2.sub(out, vecA, vecB); -out = vec2.multiply(out, vecA, vecB); -out = vec2.mul(out, vecA, vecB); -out = vec2.divide(out, vecA, vecB); -out = vec2.div(out, vecA, vecB); -out = vec2.min(out, vecA, vecB); -out = vec2.max(out, vecA, vecB); -out = vec2.scale(out, vecA, 2); -out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec2.distance(vecA, vecB); -outVal = vec2.dist(vecA, vecB); -outVal = vec2.squaredDistance(vecA, vecB); -outVal = vec2.sqrDist(vecA, vecB); -outVal = vec2.length(vecA); -outVal = vec2.len(vecA); -outVal = vec2.squaredLength(vecA); -outVal = vec2.sqrLen(vecA); -out = vec2.negate(out, vecA); -out = vec2.inverse(out, vecA); -out = vec2.normalize(out, vecA); -outVal = vec2.dot(vecA, vecB); -out = vec2.cross(out, vecA, vecB); -out = vec2.lerp(out, vecA, vecB, 0.5); -out = vec2.random(out); -out = vec2.random(out, 5.0); -out = vec2.transformMat2(out, vecA, matA); -out = vec2.transformMat2d(out, vecA, matA); -out = vec2.transformMat3(out, vecA, matA); -out = vec2.transformMat4(out, vecA, matA); -out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); -outStr = vec2.str(vecA); +outVec2 = vec2.create(); +outVec2 = vec2.clone(vec2A); +outVec2 = vec2.fromValues(1, 2); +outVec2 = vec2.copy(outVec2, vec2A); +outVec2 = vec2.set(outVec2, 1, 2); +outVec2 = vec2.add(outVec2, vec2A, vec2B); +outVec2 = vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = vec2.sub(outVec2, vec2A, vec2B); +outVec2 = vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = vec2.mul(outVec2, vec2A, vec2B); +outVec2 = vec2.divide(outVec2, vec2A, vec2B); +outVec2 = vec2.div(outVec2, vec2A, vec2B); +outVec2 = vec2.ceil(outVec2, vec2A); +outVec2 = vec2.floor(outVec2, vec2A); +outVec2 = vec2.min(outVec2, vec2A, vec2B); +outVec2 = vec2.max(outVec2, vec2A, vec2B); +outVec2 = vec2.round(outVec2, vec2A); +outVec2 = vec2.scale(outVec2, vec2A, 2); +outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = vec2.distance(vec2A, vec2B); +outVal = vec2.dist(vec2A, vec2B); +outVal = vec2.squaredDistance(vec2A, vec2B); +outVal = vec2.sqrDist(vec2A, vec2B); +outVal = vec2.length(vec2A); +outVal = vec2.len(vec2A); +outVal = vec2.squaredLength(vec2A); +outVal = vec2.sqrLen(vec2A); +outVec2 = vec2.negate(outVec2, vec2A); +outVec2 = vec2.inverse(outVec2, vec2A); +outVec2 = vec2.normalize(outVec2, vec2A); +outVal = vec2.dot(vec2A, vec2B); +outVec2 = vec2.cross(outVec2, vec2A, vec2B); +outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = vec2.random(outVec2); +outVec2 = vec2.random(outVec2, 5.0); +outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vec2A); +outBool = vec2.exactEquals(vec2A, vec2B); +outBool = vec2.equals(vec2A, vec2B); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 -var matr: GLM.IArray; -var q: GLM.IArray; - -vecA = [1, 2, 3]; -vecB = new Float32Array([4, 5, 6]); -out = [0, 0, 0]; -vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; -matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - -out = vec3.create(); -out = vec3.clone(vecA); -out = vec3.fromValues(1, 2, 3); -out = vec3.copy(out, vecA); -out = vec3.set(out, 1, 2, 3); -out = vec3.add(out, vecA, vecB); -out = vec3.subtract(out, vecA, vecB); -out = vec3.sub(out, vecA, vecB); -out = vec3.multiply(out, vecA, vecB); -out = vec3.mul(out, vecA, vecB); -out = vec3.divide(out, vecA, vecB); -out = vec3.div(out, vecA, vecB); -out = vec3.min(out, vecA, vecB); -out = vec3.max(out, vecA, vecB); -out = vec3.scale(out, vecA, 2); -out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec3.distance(vecA, vecB); -outVal = vec3.dist(vecA, vecB); -outVal = vec3.squaredDistance(vecA, vecB); -outVal = vec3.sqrDist(vecA, vecB); -outVal = vec3.length(vecA); -outVal = vec3.len(vecA); -outVal = vec3.squaredLength(vecA); -outVal = vec3.sqrLen(vecA); -out = vec3.negate(out, vecA); -out = vec3.inverse(out, vecA); -out = vec3.normalize(out, vecA); -outVal = vec3.dot(vecA, vecB); -out = vec3.cross(out, vecA, vecB); -out = vec3.lerp(out, vecA, vecB, 0.5); -out = vec3.random(out); -out = vec3.random(out, 5.0); -out = vec3.rotateX(out, vecA, vecB, Math.PI); -out = vec3.rotateY(out, vecA, vecB, Math.PI); -out = vec3.rotateZ(out, vecA, vecB, Math.PI); -out = vec3.transformMat3(out, vecA, matr); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; -out = vec3.transformMat4(out, vecA, matr); - -q = [1, 2, 3, 4]; -out = vec3.transformQuat(out, vecA, matr); - -out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); -outVal = vec3.angle(vecA, vecB); -outStr = vec3.str(vecA); +outVec3 = vec3.create(); +outVec3 = vec3.clone(vec3A); +outVec3 = vec3.fromValues(1, 2, 3); +outVec3 = vec3.copy(outVec3, vec3A); +outVec3 = vec3.set(outVec3, 1, 2, 3); +outVec3 = vec3.add(outVec3, vec3A, vec3B); +outVec3 = vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = vec3.sub(outVec3, vec3A, vec3B); +outVec3 = vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = vec3.mul(outVec3, vec3A, vec3B); +outVec3 = vec3.divide(outVec3, vec3A, vec3B); +outVec3 = vec3.div(outVec3, vec3A, vec3B); +outVec3 = vec3.ceil(outVec3, vec3A); +outVec3 = vec3.floor(outVec3, vec3A); +outVec3 = vec3.min(outVec3, vec3A, vec3B); +outVec3 = vec3.max(outVec3, vec3A, vec3B); +outVec3 = vec3.round(outVec3, vec3A); +outVec3 = vec3.scale(outVec3, vec3A, 2); +outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = vec3.distance(vec3A, vec3B); +outVal = vec3.dist(vec3A, vec3B); +outVal = vec3.squaredDistance(vec3A, vec3B); +outVal = vec3.sqrDist(vec3A, vec3B); +outVal = vec3.length(vec3A); +outVal = vec3.len(vec3A); +outVal = vec3.squaredLength(vec3A); +outVal = vec3.sqrLen(vec3A); +outVec3 = vec3.negate(outVec3, vec3A); +outVec3 = vec3.inverse(outVec3, vec3A); +outVec3 = vec3.normalize(outVec3, vec3A); +outVal = vec3.dot(vec3A, vec3B); +outVec3 = vec3.cross(outVec3, vec3A, vec3B); +outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.random(outVec3); +outVec3 = vec3.random(outVec3, 5.0); +outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vec3A, vec3B); +outStr = vec3.str(vec3A); +outBool = vec3.exactEquals(vec3A, vec3B); +outBool = vec3.equals(vec3A, vec3B); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 -var q: GLM.IArray; - -vecA = [1, 2, 3, 4]; -vecB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -q = [1, 2, 3, 4]; - -out = vec4.create(); -out = vec4.clone(vecA); -out = vec4.fromValues(1, 2, 3, 4); -out = vec4.copy(out, vecA); -out = vec4.set(out, 1, 2, 3, 4); -out = vec4.add(out, vecA, vecB); -out = vec4.subtract(out, vecA, vecB); -out = vec4.sub(out, vecA, vecB); -out = vec4.multiply(out, vecA, vecB); -out = vec4.mul(out, vecA, vecB); -out = vec4.divide(out, vecA, vecB); -out = vec4.div(out, vecA, vecB); -out = vec4.min(out, vecA, vecB); -out = vec4.max(out, vecA, vecB); -out = vec4.scale(out, vecA, 2); -out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec4.distance(vecA, vecB); -outVal = vec4.dist(vecA, vecB); -outVal = vec4.squaredDistance(vecA, vecB); -outVal = vec4.sqrDist(vecA, vecB); -outVal = vec4.length(vecA); -outVal = vec4.len(vecA); -outVal = vec4.squaredLength(vecA); -outVal = vec4.sqrLen(vecA); -out = vec4.negate(out, vecA); -out = vec4.inverse(out, vecA); -out = vec4.normalize(out, vecA); -outVal = vec4.dot(vecA, vecB); -out = vec4.lerp(out, vecA, vecB, 0.5); -out = vec4.random(out); -out = vec4.random(out, 5.0); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] -out = vec4.transformMat4(out, vecA, matr); -out = vec4.transformQuat(out, vecA, q); - -vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; -out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); -outStr = vec4.str(vecA); +outVec4 = vec4.create(); +outVec4 = vec4.clone(vec4A); +outVec4 = vec4.fromValues(1, 2, 3, 4); +outVec4 = vec4.copy(outVec4, vec4A); +outVec4 = vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = vec4.add(outVec4, vec4A, vec4B); +outVec4 = vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = vec4.sub(outVec4, vec4A, vec4B); +outVec4 = vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = vec4.mul(outVec4, vec4A, vec4B); +outVec4 = vec4.divide(outVec4, vec4A, vec4B); +outVec4 = vec4.div(outVec4, vec4A, vec4B); +outVec4 = vec4.ceil(outVec4, vec4A); +outVec4 = vec4.floor(outVec4, vec4A); +outVec4 = vec4.min(outVec4, vec4A, vec4B); +outVec4 = vec4.max(outVec4, vec4A, vec4B); +outVec4 = vec4.scale(outVec4, vec4A, 2); +outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = vec4.distance(vec4A, vec4B); +outVal = vec4.dist(vec4A, vec4B); +outVal = vec4.squaredDistance(vec4A, vec4B); +outVal = vec4.sqrDist(vec4A, vec4B); +outVal = vec4.length(vec4A); +outVal = vec4.len(vec4A); +outVal = vec4.squaredLength(vec4A); +outVal = vec4.sqrLen(vec4A); +outVec4 = vec4.negate(outVec4, vec4A); +outVec4 = vec4.inverse(outVec4, vec4A); +outVec4 = vec4.normalize(outVec4, vec4A); +outVal = vec4.dot(vec4A, vec4B); +outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = vec4.random(outVec4); +outVec4 = vec4.random(outVec4, 5.0); +outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vec4A); +outBool = vec4.exactEquals(vec4A, vec4B); +outBool = vec4.equals(vec4A, vec4B); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 -var matB: GLM.IArray, identity: GLM.IArray; - -matA = [1, 2, 3, 4]; -matB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -identity = [1, 0, 0, 1]; - -out = mat2.create(); -out = mat2.clone(matA); -out = mat2.copy(out, matA); -out = mat2.identity(out); -out = mat2.transpose(out, matA); -out = mat2.invert(out, matA); -out = mat2.adjoint(out, matA); -outVal = mat2.determinant(matA); -out = mat2.multiply(out, matA, matB); -out = mat2.mul(out, matA, matB); -out = mat2.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2.scale(out, matA, vecA); -outStr = mat2.str(matA); -outVal = mat2.frob(matA); - -var L = mat2.create(); -var D = mat2.create(); +outMat2 = mat2.create(); +outMat2 = mat2.clone(mat2A); +outMat2 = mat2.copy(outMat2, mat2A); +outMat2 = mat2.identity(outMat2); +outMat2 = mat2.fromValues(1, 2, 3, 4); +outMat2 = mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = mat2.transpose(outMat2, mat2A); +outMat2 = mat2.invert(outMat2, mat2A); +outMat2 = mat2.adjoint(outMat2, mat2A); +outVal = mat2.determinant(mat2A); +outMat2 = mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = mat2.mul(outMat2, mat2A, mat2B); +outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = mat2.scale(outMat2, mat2A, vec2A); +outMat2 = mat2.fromRotation(outMat2, 0.5); +outMat2 = mat2.fromScaling(outMat2, vec2A); +outStr = mat2.str(mat2A); +outVal = mat2.frob(mat2A); +var L = mat2.create(); +var D = mat2.create(); var U = mat2.create(); -out = mat2.LDU(L, D, U, [4,3,6,3]); +outMat2 = mat2.LDU(L, D, U, mat2A); +outMat2 = mat2.add(outMat2, mat2A, mat2B); +outMat2 = mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = mat2.sub(outMat2, mat2A, mat2B); +outBool = mat2.exactEquals(mat2A, mat2B); +outBool = mat2.equals(mat2A, mat2B); +outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); // mat2d -matA = [1, 2, 3, 4, 5, 6]; -matB = [7, 8, 9, 10, 11, 12]; -out = [0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 1, 0, 0]; - -out = mat2d.create(); -out = mat2d.clone(matA); -out = mat2d.copy(out, matA); -out = mat2d.identity(out); -out = mat2d.invert(out, matA); -outVal = mat2d.determinant(matA); -out = mat2d.multiply(out, matA, matB); -out = mat2d.mul(out, matA, matB); -out = mat2d.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2d.scale(out, matA, vecA); -out = mat2d.translate(out, matA, vecA); -outStr = mat2d.str(matA); -outVal = mat2d.frob(matA); +outMat2d = mat2d.create(); +outMat2d = mat2d.clone(mat2dA); +outMat2d = mat2d.copy(outMat2d, mat2dA); +outMat2d = mat2d.identity(outMat2d); +outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = mat2d.invert(outMat2d, mat2dA); +outVal = mat2d.determinant(mat2dA); +outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.fromRotation(outMat2d, 0.5); +outMat2d = mat2d.fromScaling(outMat2d, vec2A); +outMat2d = mat2d.fromTranslation(outMat2d, vec2A); +outStr = mat2d.str(mat2dA); +outVal = mat2d.frob(mat2dA); +outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = mat2d.exactEquals(mat2dA, mat2dB); +outBool = mat2d.equals(mat2dA, mat2dB); // mat3 -matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; -matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; -out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - -out = mat3.create(); -out = mat3.clone(matA); -out = mat3.copy(out, matA); -out = mat3.identity(out); -out = mat3.transpose(out, matA); -out = mat3.invert(out, matA); -out = mat3.adjoint(out, matA); -outVal = mat3.determinant(matA); -out = mat3.multiply(out, matA, matB); -out = mat3.mul(out, matA, matB); -outStr = mat3.str(matA); -outVal = mat3.frob(matA); - -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; -out = mat3.normalFromMat4(out, matA); - -q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; -out = mat3.fromQuat(out, q); - -out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.scale(out, matA, [2,2]); -out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); - -out = mat3.translate(out, matA, [1, 2, 3]); -out = mat3.rotate(out, matA, Math.PI/2); - -// mat4 -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 1, 2, 3, 1]; - -matB = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 4, 5, 6, 1]; - -out = [0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]; - -identity = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; - -out = mat4.create(); -out = mat4.clone(matA); -out = mat4.copy(out, matA); -out = mat4.identity(out); -out = mat4.transpose(out, matA); -out = mat4.invert(out, matA); -out = mat4.adjoint(out, matA); -outVal = mat4.determinant(matA); -out = mat4.multiply(out, matA, matB); -out = mat4.mul(out, matA, matB); -out = mat4.translate(out, matA, [4, 5, 6]); -out = mat4.scale(out, matA, [4, 5, 6]); - -var rad = Math.PI * 0.5; -var axis = [1, 0, 0]; -out = mat4.rotate(out, matA, rad, axis); -out = mat4.rotateX(out, matA, rad); -out = mat4.rotateY(out, matA, rad); -out = mat4.rotateZ(out, matA, rad); - -out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); - -var fovy = Math.PI * 0.5; -out = mat4.perspective(out, fovy, 1, 0, 1); -out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); - -var eye = [0, 0, 1]; -var center = [0, 0, -1]; -var up = [0, 1, 0]; -out = mat4.lookAt(out, eye, center, up); - -outStr = mat4.str(matA); -outVal = mat4.frob(matA); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); -out = mat4.fromQuat(out, q); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); -out = mat4.fromQuat(out, q); +outMat3 = mat3.create(); +outMat3 = mat3.fromMat4(outMat3, mat4A); +outMat3 = mat3.clone(mat3A); +outMat3 = mat3.copy(outMat3, mat3A); +outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.identity(outMat3); +outMat3 = mat3.transpose(outMat3, mat3A); +outMat3 = mat3.invert(outMat3, mat3A); +outMat3 = mat3.adjoint(outMat3, mat3A); +outVal = mat3.determinant(mat3A); +outMat3 = mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = mat3.mul(outMat3, mat3A, mat3B); +outMat3 = mat3.translate(outMat3, mat3A, vec3A); +outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = mat3.scale(outMat3, mat3A, vec2A); +outMat3 = mat3.fromTranslation(outMat3, vec2A); +outMat3 = mat3.fromRotation(outMat3, Math.PI); +outMat3 = mat3.fromScaling(outMat3, vec2A); +outMat3 = mat3.fromMat2d(outMat3, mat2dA); +outMat3 = mat3.fromQuat(outMat3, quatA); +outMat3 = mat3.normalFromMat4(outMat3, mat4A); +outStr = mat3.str(mat3A); +outVal = mat3.frob(mat3A); +outMat3 = mat3.add(outMat3, mat3A, mat3B); +outMat3 = mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = mat3.sub(outMat3, mat3A, mat3B); +outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = mat3.exactEquals(mat3A, mat3B); +outBool = mat3.equals(mat3A, mat3B); +//mat4 +outMat4 = mat4.create(); +outMat4 = mat4.clone(mat4A); +outMat4 = mat4.copy(outMat4, mat4A); +outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.identity(outMat4); +outMat4 = mat4.transpose(outMat4, mat4A); +outMat4 = mat4.invert(outMat4, mat4A); +outMat4 = mat4.adjoint(outMat4, mat4A); +outVal = mat4.determinant(mat4A); +outMat4 = mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = mat4.mul(outMat4, mat4A, mat4B); +outMat4 = mat4.translate(outMat4, mat4A, vec3A); +outMat4 = mat4.scale(outMat4, mat4A, vec3A); +outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = mat4.fromTranslation(outMat4, vec3A); +outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = mat4.fromScaling(outMat4, vec3A); +outMat4 = mat4.fromXRotation(outMat4, Math.PI); +outMat4 = mat4.fromYRotation(outMat4, Math.PI); +outMat4 = mat4.fromZRotation(outMat4, Math.PI); +outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = mat4.getTranslation(outVec3, mat4A) +outQuat = mat4.getRotation(outQuat, mat4A) +outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = mat4.fromQuat(outMat4, quatB); +outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = mat4.str(mat4A); +outVal = mat4.frob(mat4A); +outMat4 = mat4.add(outMat4, mat4A, mat4B); +outMat4 = mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = mat4.sub(outMat4, mat4A, mat4B); +outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = mat4.exactEquals(mat4A, mat4B); +outBool = mat4.equals(mat4A, mat4B); // quat -var quatA = [1, 2, 3, 4]; -var quatB = [5, 6, 7, 8]; -out = [0, 0, 0, 0]; -var vec = [1, 1, -1]; -var id = [0, 0, 0, 1]; var deg90 = Math.PI / 2; - -out = quat.create(); -out = quat.clone(quatA); -out = quat.fromValues(1, 2, 3, 4); -out = quat.copy(out, quatA); -out = quat.set(out, 1, 2, 3, 4); -out = quat.identity(out); -out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); -out = quat.add(out, quatA, quatB); -out = quat.multiply(out, quatA, quatB); -out = quat.mul(out, quatA, quatB); -out = quat.scale(out, quatA, 2); +outQuat = quat.create(); +outQuat = quat.clone(quatA); +outQuat = quat.fromValues(1, 2, 3, 4); +outQuat = quat.copy(outQuat, quatA); +outQuat = quat.set(outQuat, 1, 2, 3, 4); +outQuat = quat.identity(outQuat); +outQuat = quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = quat.getAxisAngle (outVec3, quatA); +outQuat = quat.add(outQuat, quatA, quatB); +outQuat = quat.multiply(outQuat, quatA, quatB); +outQuat = quat.mul(outQuat, quatA, quatB); +outQuat = quat.scale(outQuat, quatA, 2); outVal = quat.length(quatA); outVal = quat.len(quatA); outVal = quat.squaredLength(quatA); outVal = quat.sqrLen(quatA); -out = quat.normalize(out, quatA); -outVal = quat.dot(out, quatA, quatB); -out = quat.lerp(out, quatA, quatB, 0.5); -out = quat.slerp(out, quatA, quatB, 0.5); -out = quat.invert(out, quatA); -out = quat.conjugate(out, quatA); +outQuat = quat.normalize(outQuat, quatA); +outVal = quat.dot(quatA, quatB); +outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.invert(outQuat, quatA); +outQuat = quat.conjugate(outQuat, quatA); outStr = quat.str(quatA); -out = quat.rotateX(out, id, deg90); -out = quat.rotateY(out, id, deg90); -out = quat.rotateZ(out, id, deg90); - -matr = [ 1, 0, 0, - 0, 0, -1, - 0, 1, 0 ]; -out = quat.fromMat3(out, matr); - -var view = [-1, 0, 0]; -up = [ 0, 1, 0]; -var right= [ 0, 0,-1]; -out = quat.setAxes([], view, right, up); - -out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); -out = quat.calculateW(out, quatA); - +outQuat = quat.rotateX(outQuat, quatA, deg90); +outQuat = quat.rotateY(outQuat, quatA, deg90); +outQuat = quat.rotateZ(outQuat, quatA, deg90); +outQuat = quat.fromMat3(outQuat, mat3A); +outQuat = quat.calculateW(outQuat, quatA); +outBool = quat.exactEquals(quatA, quatB); +outBool = quat.equals(quatA, quatB); diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts deleted file mode 100644 index 64f6beb7a4..0000000000 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ /dev/null @@ -1,347 +0,0 @@ -/// - -// common -import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix-typed"; - -var outVal: number; -var outBool: boolean; -var outStr: string; - -let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); - -let vec2A = vec2.fromValues(1, 2); -let vec2B = vec2.fromValues(3, 4); -let vec3A = vec3.fromValues(1, 2, 3); -let vec3B = vec3.fromValues(3, 4, 5); -let vec4A = vec4.fromValues(1, 2, 3, 4); -let vec4B = vec4.fromValues(3, 4, 5, 6); -let mat2A = mat2.fromValues(1, 2, 3, 4); -let mat2B = mat2.fromValues(1, 2, 3, 4); -let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); -let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); -let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); -let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); -let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -let quatA = quat.fromValues(1, 2, 3, 4); -let quatB = quat.fromValues(5, 6, 7, 8); - -let outVec2 = vec2.create(); -let outVec3 = vec3.create(); -let outVec4 = vec4.create(); -let outMat2 = mat2.create(); -let outMat2d = mat2d.create(); -let outMat3 = mat3.create(); -let outMat4 = mat4.create(); -let outQuat = quat.create(); - -// vec2 -outVec2 = vec2.create(); -outVec2 = vec2.clone(vec2A); -outVec2 = vec2.fromValues(1, 2); -outVec2 = vec2.copy(outVec2, vec2A); -outVec2 = vec2.set(outVec2, 1, 2); -outVec2 = vec2.add(outVec2, vec2A, vec2B); -outVec2 = vec2.subtract(outVec2, vec2A, vec2B); -outVec2 = vec2.sub(outVec2, vec2A, vec2B); -outVec2 = vec2.multiply(outVec2, vec2A, vec2B); -outVec2 = vec2.mul(outVec2, vec2A, vec2B); -outVec2 = vec2.divide(outVec2, vec2A, vec2B); -outVec2 = vec2.div(outVec2, vec2A, vec2B); -outVec2 = vec2.ceil(outVec2, vec2A); -outVec2 = vec2.floor(outVec2, vec2A); -outVec2 = vec2.min(outVec2, vec2A, vec2B); -outVec2 = vec2.max(outVec2, vec2A, vec2B); -outVec2 = vec2.round(outVec2, vec2A); -outVec2 = vec2.scale(outVec2, vec2A, 2); -outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); -outVal = vec2.distance(vec2A, vec2B); -outVal = vec2.dist(vec2A, vec2B); -outVal = vec2.squaredDistance(vec2A, vec2B); -outVal = vec2.sqrDist(vec2A, vec2B); -outVal = vec2.length(vec2A); -outVal = vec2.len(vec2A); -outVal = vec2.squaredLength(vec2A); -outVal = vec2.sqrLen(vec2A); -outVec2 = vec2.negate(outVec2, vec2A); -outVec2 = vec2.inverse(outVec2, vec2A); -outVec2 = vec2.normalize(outVec2, vec2A); -outVal = vec2.dot(vec2A, vec2B); -outVec2 = vec2.cross(outVec2, vec2A, vec2B); -outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); -outVec2 = vec2.random(outVec2); -outVec2 = vec2.random(outVec2, 5.0); -outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); -outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); -outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); -outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); -vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); -outStr = vec2.str(vec2A); -outBool = vec2.exactEquals(vec2A, vec2B); -outBool = vec2.equals(vec2A, vec2B); -outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input - -// vec3 -outVec3 = vec3.create(); -outVec3 = vec3.clone(vec3A); -outVec3 = vec3.fromValues(1, 2, 3); -outVec3 = vec3.copy(outVec3, vec3A); -outVec3 = vec3.set(outVec3, 1, 2, 3); -outVec3 = vec3.add(outVec3, vec3A, vec3B); -outVec3 = vec3.subtract(outVec3, vec3A, vec3B); -outVec3 = vec3.sub(outVec3, vec3A, vec3B); -outVec3 = vec3.multiply(outVec3, vec3A, vec3B); -outVec3 = vec3.mul(outVec3, vec3A, vec3B); -outVec3 = vec3.divide(outVec3, vec3A, vec3B); -outVec3 = vec3.div(outVec3, vec3A, vec3B); -outVec3 = vec3.ceil(outVec3, vec3A); -outVec3 = vec3.floor(outVec3, vec3A); -outVec3 = vec3.min(outVec3, vec3A, vec3B); -outVec3 = vec3.max(outVec3, vec3A, vec3B); -outVec3 = vec3.round(outVec3, vec3A); -outVec3 = vec3.scale(outVec3, vec3A, 2); -outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); -outVal = vec3.distance(vec3A, vec3B); -outVal = vec3.dist(vec3A, vec3B); -outVal = vec3.squaredDistance(vec3A, vec3B); -outVal = vec3.sqrDist(vec3A, vec3B); -outVal = vec3.length(vec3A); -outVal = vec3.len(vec3A); -outVal = vec3.squaredLength(vec3A); -outVal = vec3.sqrLen(vec3A); -outVec3 = vec3.negate(outVec3, vec3A); -outVec3 = vec3.inverse(outVec3, vec3A); -outVec3 = vec3.normalize(outVec3, vec3A); -outVal = vec3.dot(vec3A, vec3B); -outVec3 = vec3.cross(outVec3, vec3A, vec3B); -outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); -outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); -outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); -outVec3 = vec3.random(outVec3); -outVec3 = vec3.random(outVec3, 5.0); -outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); -outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); -outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); -outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); -outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); -outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); -vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); -outVal = vec3.angle(vec3A, vec3B); -outStr = vec3.str(vec3A); -outBool = vec3.exactEquals(vec3A, vec3B); -outBool = vec3.equals(vec3A, vec3B); -outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input - -// vec4 -outVec4 = vec4.create(); -outVec4 = vec4.clone(vec4A); -outVec4 = vec4.fromValues(1, 2, 3, 4); -outVec4 = vec4.copy(outVec4, vec4A); -outVec4 = vec4.set(outVec4, 1, 2, 3, 4); -outVec4 = vec4.add(outVec4, vec4A, vec4B); -outVec4 = vec4.subtract(outVec4, vec4A, vec4B); -outVec4 = vec4.sub(outVec4, vec4A, vec4B); -outVec4 = vec4.multiply(outVec4, vec4A, vec4B); -outVec4 = vec4.mul(outVec4, vec4A, vec4B); -outVec4 = vec4.divide(outVec4, vec4A, vec4B); -outVec4 = vec4.div(outVec4, vec4A, vec4B); -outVec4 = vec4.ceil(outVec4, vec4A); -outVec4 = vec4.floor(outVec4, vec4A); -outVec4 = vec4.min(outVec4, vec4A, vec4B); -outVec4 = vec4.max(outVec4, vec4A, vec4B); -outVec4 = vec4.scale(outVec4, vec4A, 2); -outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); -outVal = vec4.distance(vec4A, vec4B); -outVal = vec4.dist(vec4A, vec4B); -outVal = vec4.squaredDistance(vec4A, vec4B); -outVal = vec4.sqrDist(vec4A, vec4B); -outVal = vec4.length(vec4A); -outVal = vec4.len(vec4A); -outVal = vec4.squaredLength(vec4A); -outVal = vec4.sqrLen(vec4A); -outVec4 = vec4.negate(outVec4, vec4A); -outVec4 = vec4.inverse(outVec4, vec4A); -outVec4 = vec4.normalize(outVec4, vec4A); -outVal = vec4.dot(vec4A, vec4B); -outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); -outVec4 = vec4.random(outVec4); -outVec4 = vec4.random(outVec4, 5.0); -outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); -outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); -vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); -outStr = vec4.str(vec4A); -outBool = vec4.exactEquals(vec4A, vec4B); -outBool = vec4.equals(vec4A, vec4B); -outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input - -// mat2 -outMat2 = mat2.create(); -outMat2 = mat2.clone(mat2A); -outMat2 = mat2.copy(outMat2, mat2A); -outMat2 = mat2.identity(outMat2); -outMat2 = mat2.fromValues(1, 2, 3, 4); -outMat2 = mat2.set(outMat2, 1, 2, 3, 4); -outMat2 = mat2.transpose(outMat2, mat2A); -outMat2 = mat2.invert(outMat2, mat2A); -outMat2 = mat2.adjoint(outMat2, mat2A); -outVal = mat2.determinant(mat2A); -outMat2 = mat2.multiply(outMat2, mat2A, mat2B); -outMat2 = mat2.mul(outMat2, mat2A, mat2B); -outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); -outMat2 = mat2.scale(outMat2, mat2A, vec2A); -outMat2 = mat2.fromRotation(outMat2, 0.5); -outMat2 = mat2.fromScaling(outMat2, vec2A); -outStr = mat2.str(mat2A); -outVal = mat2.frob(mat2A); -var L = mat2.create(); -var D = mat2.create(); -var U = mat2.create(); -outMat2 = mat2.LDU(L, D, U, mat2A); -outMat2 = mat2.add(outMat2, mat2A, mat2B); -outMat2 = mat2.subtract(outMat2, mat2A, mat2B); -outMat2 = mat2.sub(outMat2, mat2A, mat2B); -outBool = mat2.exactEquals(mat2A, mat2B); -outBool = mat2.equals(mat2A, mat2B); -outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); -outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); - -// mat2d -outMat2d = mat2d.create(); -outMat2d = mat2d.clone(mat2dA); -outMat2d = mat2d.copy(outMat2d, mat2dA); -outMat2d = mat2d.identity(outMat2d); -outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); -outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); -outMat2d = mat2d.invert(outMat2d, mat2dA); -outVal = mat2d.determinant(mat2dA); -outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); -outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); -outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); -outMat2d = mat2d.fromRotation(outMat2d, 0.5); -outMat2d = mat2d.fromScaling(outMat2d, vec2A); -outMat2d = mat2d.fromTranslation(outMat2d, vec2A); -outStr = mat2d.str(mat2dA); -outVal = mat2d.frob(mat2dA); -outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); -outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); -outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); -outBool = mat2d.exactEquals(mat2dA, mat2dB); -outBool = mat2d.equals(mat2dA, mat2dB); - -// mat3 -outMat3 = mat3.create(); -outMat3 = mat3.fromMat4(outMat3, mat4A); -outMat3 = mat3.clone(mat3A); -outMat3 = mat3.copy(outMat3, mat3A); -outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); -outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); -outMat3 = mat3.identity(outMat3); -outMat3 = mat3.transpose(outMat3, mat3A); -outMat3 = mat3.invert(outMat3, mat3A); -outMat3 = mat3.adjoint(outMat3, mat3A); -outVal = mat3.determinant(mat3A); -outMat3 = mat3.multiply(outMat3, mat3A, mat3B); -outMat3 = mat3.mul(outMat3, mat3A, mat3B); -outMat3 = mat3.translate(outMat3, mat3A, vec3A); -outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); -outMat3 = mat3.scale(outMat3, mat3A, vec2A); -outMat3 = mat3.fromTranslation(outMat3, vec2A); -outMat3 = mat3.fromRotation(outMat3, Math.PI); -outMat3 = mat3.fromScaling(outMat3, vec2A); -outMat3 = mat3.fromMat2d(outMat3, mat2dA); -outMat3 = mat3.fromQuat(outMat3, quatA); -outMat3 = mat3.normalFromMat4(outMat3, mat4A); -outStr = mat3.str(mat3A); -outVal = mat3.frob(mat3A); -outMat3 = mat3.add(outMat3, mat3A, mat3B); -outMat3 = mat3.subtract(outMat3, mat3A, mat3B); -outMat3 = mat3.sub(outMat3, mat3A, mat3B); -outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); -outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); -outBool = mat3.exactEquals(mat3A, mat3B); -outBool = mat3.equals(mat3A, mat3B); - -//mat4 -outMat4 = mat4.create(); -outMat4 = mat4.clone(mat4A); -outMat4 = mat4.copy(outMat4, mat4A); -outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); -outMat4 = mat4.identity(outMat4); -outMat4 = mat4.transpose(outMat4, mat4A); -outMat4 = mat4.invert(outMat4, mat4A); -outMat4 = mat4.adjoint(outMat4, mat4A); -outVal = mat4.determinant(mat4A); -outMat4 = mat4.multiply(outMat4, mat4A, mat4B); -outMat4 = mat4.mul(outMat4, mat4A, mat4B); -outMat4 = mat4.translate(outMat4, mat4A, vec3A); -outMat4 = mat4.scale(outMat4, mat4A, vec3A); -outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); -outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); -outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); -outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); -outMat4 = mat4.fromTranslation(outMat4, vec3A); -outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); -outMat4 = mat4.fromScaling(outMat4, vec3A); -outMat4 = mat4.fromXRotation(outMat4, Math.PI); -outMat4 = mat4.fromYRotation(outMat4, Math.PI); -outMat4 = mat4.fromZRotation(outMat4, Math.PI); -outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); -outVec3 = mat4.getTranslation(outVec3, mat4A) -outQuat = mat4.getRotation(outQuat, mat4A) -outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); -outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); -outMat4 = mat4.fromQuat(outMat4, quatB); -outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); -outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); -outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); -outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); -outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); -outStr = mat4.str(mat4A); -outVal = mat4.frob(mat4A); -outMat4 = mat4.add(outMat4, mat4A, mat4B); -outMat4 = mat4.subtract(outMat4, mat4A, mat4B); -outMat4 = mat4.sub(outMat4, mat4A, mat4B); -outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); -outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); -outBool = mat4.exactEquals(mat4A, mat4B); -outBool = mat4.equals(mat4A, mat4B); - -// quat -var deg90 = Math.PI / 2; -outQuat = quat.create(); -outQuat = quat.clone(quatA); -outQuat = quat.fromValues(1, 2, 3, 4); -outQuat = quat.copy(outQuat, quatA); -outQuat = quat.set(outQuat, 1, 2, 3, 4); -outQuat = quat.identity(outQuat); -outQuat = quat.rotationTo(outQuat, vec3A, vec3B); -outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); -outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); -outVal = quat.getAxisAngle (outVec3, quatA); -outQuat = quat.add(outQuat, quatA, quatB); -outQuat = quat.multiply(outQuat, quatA, quatB); -outQuat = quat.mul(outQuat, quatA, quatB); -outQuat = quat.scale(outQuat, quatA, 2); -outVal = quat.length(quatA); -outVal = quat.len(quatA); -outVal = quat.squaredLength(quatA); -outVal = quat.sqrLen(quatA); -outQuat = quat.normalize(outQuat, quatA); -outVal = quat.dot(quatA, quatB); -outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); -outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); -outQuat = quat.invert(outQuat, quatA); -outQuat = quat.conjugate(outQuat, quatA); -outStr = quat.str(quatA); -outQuat = quat.rotateX(outQuat, quatA, deg90); -outQuat = quat.rotateY(outQuat, quatA, deg90); -outQuat = quat.rotateZ(outQuat, quatA, deg90); -outQuat = quat.fromMat3(outQuat, mat3A); -outQuat = quat.calculateW(outQuat, quatA); -outBool = quat.exactEquals(quatA, quatB); -outBool = quat.equals(quatA, quatB); \ No newline at end of file diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts deleted file mode 100644 index 2edbbd8bb5..0000000000 --- a/gl-matrix/gl-matrix-typed.d.ts +++ /dev/null @@ -1,3044 +0,0 @@ -// Type definitions for gl-matrix 2.2.2 -// Project: https://github.com/toji/gl-matrix -// Definitions by: Mattijs Kneppers , based on definitions by Tat -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// vec2 -export class vec2 extends Float32Array { - private typeVec2: number; - - /** - * Creates a new, empty vec2 - * - * @returns a new 2D vector - */ - public static create(): vec2; - - /** - * Creates a new vec2 initialized with values from an existing vector - * - * @param a a vector to clone - * @returns a new 2D vector - */ - public static clone(a: vec2 | number[]): vec2; - - /** - * Creates a new vec2 initialized with the given values - * - * @param x X component - * @param y Y component - * @returns a new 2D vector - */ - public static fromValues(x: number, y: number): vec2; - - /** - * Copy the values from one vec2 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec2, a: vec2 | number[]): vec2; - - /** - * Set the components of a vec2 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @returns out - */ - public static set(out: vec2, x: number, y: number): vec2; - - /** - * Adds two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Multiplies two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Divides two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Math.ceil the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to ceil - * @returns {vec2} out - */ - public static ceil(out: vec2, a: vec2 | number[]): vec2; - - /** - * Math.floor the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to floor - * @returns {vec2} out - */ - public static floor (out: vec2, a: vec2 | number[]): vec2; - - /** - * Returns the minimum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Returns the maximum of two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Math.round the components of a vec2 - * - * @param {vec2} out the receiving vector - * @param {vec2} a vector to round - * @returns {vec2} out - */ - public static round(out: vec2, a: vec2 | number[]): vec2; - - - /** - * Scales a vec2 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec2, a: vec2 | number[], b: number): vec2; - - /** - * Adds two vec2's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; - - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec2 | number[]): number; - - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec2 | number[]): number; - - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec2 | number[]): number; - - /** - * Calculates the squared length of a vec2 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec2 | number[]): number; - - /** - * Negates the components of a vec2 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec2, a: vec2 | number[]): vec2; - - /** - * Returns the inverse of the components of a vec2 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec2, a: vec2 | number[]): vec2; - - /** - * Normalize a vec2 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec2, a: vec2 | number[]): vec2; - - /** - * Calculates the dot product of two vec2's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec2 | number[], b: vec2 | number[]): number; - - /** - * Computes the cross product of two vec2's - * Note that the cross product must by definition produce a 3D vector - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; - - /** - * Performs a linear interpolation between two vec2's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec2): vec2; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec2, scale: number): vec2; - - /** - * Transforms the vec2 with a mat2 - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; - - /** - * Transforms the vec2 with a mat2d - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; - - /** - * Transforms the vec2 with a mat3 - * 3rd vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; - - /** - * Transforms the vec2 with a mat4 - * 3rd vector component is implicitly '0' - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; - - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec2s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec2s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec2 | number[]): string; - - /** - * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec2} a The first vector. - * @param {vec2} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; -} - -// vec3 -export class vec3 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec3 - * - * @returns a new 3D vector - */ - public static create(): vec3; - - /** - * Creates a new vec3 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 3D vector - */ - public static clone(a: vec3 | number[]): vec3; - - /** - * Creates a new vec3 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @returns a new 3D vector - */ - public static fromValues(x: number, y: number, z: number): vec3; - - /** - * Copy the values from one vec3 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec3, a: vec3 | number[]): vec3; - - /** - * Set the components of a vec3 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @returns out - */ - public static set(out: vec3, x: number, y: number, z: number): vec3; - - /** - * Adds two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Multiplies two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Divides two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.ceil the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to ceil - * @returns {vec3} out - */ - public static ceil (out: vec3, a: vec3 | number[]): vec3; - - /** - * Math.floor the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to floor - * @returns {vec3} out - */ - public static floor (out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the minimum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Returns the maximum of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Math.round the components of a vec3 - * - * @param {vec3} out the receiving vector - * @param {vec3} a vector to round - * @returns {vec3} out - */ - public static round (out: vec3, a: vec3 | number[]): vec3 - - /** - * Scales a vec3 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec3, a: vec3 | number[], b: number): vec3; - - /** - * Adds two vec3's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec3 | number[]): number; - - /** - * Calculates the squared length of a vec3 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec3 | number[]): number; - - /** - * Negates the components of a vec3 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec3, a: vec3 | number[]): vec3; - - /** - * Returns the inverse of the components of a vec3 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec3, a: vec3 | number[]): vec3; - - /** - * Normalize a vec3 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec3, a: vec3 | number[]): vec3; - - /** - * Calculates the dot product of two vec3's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Computes the cross product of two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; - - /** - * Performs a linear interpolation between two vec3's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; - - /** - * Performs a hermite interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Performs a bezier interpolation with two control points - * - * @param {vec3} out the receiving vector - * @param {vec3} a the first operand - * @param {vec3} b the second operand - * @param {vec3} c the third operand - * @param {vec3} d the fourth operand - * @param {number} t interpolation amount between the two inputs - * @returns {vec3} out - */ - public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec3): vec3; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec3, scale: number): vec3; - - /** - * Transforms the vec3 with a mat3. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m the 3x3 matrix to transform with - * @returns out - */ - public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; - - /** - * Transforms the vec3 with a mat4. - * 4th vector component is implicitly '1' - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - - /** - * Transforms the vec3 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; - - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec3s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec3s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; - - /** - * Get the angle between two 3D vectors - * @param a The first operand - * @param b The second operand - * @returns The angle in radians - */ - public static angle(a: vec3 | number[], b: vec3 | number[]): number; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec3 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec3} a The first vector. - * @param {vec3} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec3 | number[], b: vec3 | number[]): boolean -} - -// vec4 -export class vec4 extends Float32Array { - private typeVec3: number; - - /** - * Creates a new, empty vec4 - * - * @returns a new 4D vector - */ - public static create(): vec4; - - /** - * Creates a new vec4 initialized with values from an existing vector - * - * @param a vector to clone - * @returns a new 4D vector - */ - public static clone(a: vec4 | number[]): vec4; - - /** - * Creates a new vec4 initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new 4D vector - */ - public static fromValues(x: number, y: number, z: number, w: number): vec4; - - /** - * Copy the values from one vec4 to another - * - * @param out the receiving vector - * @param a the source vector - * @returns out - */ - public static copy(out: vec4, a: vec4 | number[]): vec4; - - /** - * Set the components of a vec4 to the given values - * - * @param out the receiving vector - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - */ - public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; - - /** - * Adds two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Subtracts vector b from vector a - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Multiplies two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Divides two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.ceil the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to ceil - * @returns {vec4} out - */ - public static ceil (out: vec4, a: vec4 | number[]): vec4; - - /** - * Math.floor the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to floor - * @returns {vec4} out - */ - public static floor (out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the minimum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Returns the maximum of two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; - - /** - * Math.round the components of a vec4 - * - * @param {vec4} out the receiving vector - * @param {vec4} a vector to round - * @returns {vec4} out - */ - public static round (out: vec4, a: vec4 | number[]): vec4; - - /** - * Scales a vec4 by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - */ - public static scale(out: vec4, a: vec4 | number[], b: number): vec4; - - /** - * Adds two vec4's after scaling the second operand by a scalar value - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param scale the amount to scale b by before adding - * @returns out - */ - public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static distance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns distance between a and b - */ - public static dist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the squared euclidian distance between two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns squared distance between a and b - */ - public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static squaredLength(a: vec4 | number[]): number; - - /** - * Calculates the squared length of a vec4 - * - * @param a vector to calculate squared length of - * @returns squared length of a - */ - public static sqrLen(a: vec4 | number[]): number; - - /** - * Negates the components of a vec4 - * - * @param out the receiving vector - * @param a vector to negate - * @returns out - */ - public static negate(out: vec4, a: vec4 | number[]): vec4; - - /** - * Returns the inverse of the components of a vec4 - * - * @param out the receiving vector - * @param a vector to invert - * @returns out - */ - public static inverse(out: vec4, a: vec4 | number[]): vec4; - - /** - * Normalize a vec4 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec4, a: vec4 | number[]): vec4; - - /** - * Calculates the dot product of two vec4's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - */ - public static dot(a: vec4 | number[], b: vec4 | number[]): number; - - /** - * Performs a linear interpolation between two vec4's - * - * @param out the receiving vector - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; - - /** - * Generates a random unit vector - * - * @param out the receiving vector - * @returns out - */ - public static random(out: vec4): vec4; - - /** - * Generates a random vector with the given scale - * - * @param out the receiving vector - * @param scale length of the resulting vector. If ommitted, a unit vector will be returned - * @returns out - */ - public static random(out: vec4, scale: number): vec4; - - /** - * Transforms the vec4 with a mat4. - * - * @param out the receiving vector - * @param a the vector to transform - * @param m matrix to transform with - * @returns out - */ - public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; - - /** - * Transforms the vec4 with a quat - * - * @param out the receiving vector - * @param a the vector to transform - * @param q quaternion to transform with - * @returns out - */ - - public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @param arg additional argument to pass to fn - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * Perform some operation over an array of vec4s. - * - * @param a the array of vectors to iterate over - * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed - * @param offset Number of elements to skip at the beginning of the array - * @param count Number of vec4s to iterate over. If 0 iterates over entire array - * @param fn Function to call for each vector in the array - * @returns a - * @function - */ - public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; - - /** - * Returns a string representation of a vector - * - * @param a vector to represent as a string - * @returns string representation of the vector - */ - public static str(a: vec4 | number[]): string; - - /** - * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; - - /** - * Returns whether or not the vectors have approximately the same elements in the same position. - * - * @param {vec4} a The first vector. - * @param {vec4} b The second vector. - * @returns {boolean} True if the vectors are equal, false otherwise. - */ - public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; -} - -// mat2 -export class mat2 extends Float32Array { - private typeMat2: number; - - /** - * Creates a new identity mat2 - * - * @returns a new 2x2 matrix - */ - public static create(): mat2; - - /** - * Creates a new mat2 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x2 matrix - */ - public static clone(a: mat2): mat2; - - /** - * Copy the values from one mat2 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2, a: mat2): mat2; - - /** - * Set a mat2 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2): mat2; - - /** - * Create a new mat2 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out A new 2x2 matrix - */ - public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Set the components of a mat2 to the given values - * - * @param {mat2} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m10 Component in column 1, row 0 position (index 2) - * @param {number} m11 Component in column 1, row 1 position (index 3) - * @returns {mat2} out - */ - public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; - - /** - * Transpose the values of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat2, a: mat2): mat2; - - /** - * Inverts a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2, a: mat2): mat2; - - /** - * Calculates the adjugate of a mat2 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat2, a: mat2): mat2; - - /** - * Calculates the determinant of a mat2 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2): number; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Multiplies two mat2's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Rotates a mat2 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2, a: mat2, rad: number): mat2; - - /** - * Scales the mat2 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.rotate(dest, dest, rad); - * - * @param {mat2} out mat2 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2} out - */ - public static fromRotation(out: mat2, rad: number): mat2; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2.identity(dest); - * mat2.scale(dest, dest, vec); - * - * @param {mat2} out mat2 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2} out - */ - public static fromScaling(out: mat2, v: vec2 | number[]): mat2; - - /** - * Returns a string representation of a mat2 - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2): string; - - /** - * Returns Frobenius norm of a mat2 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2): number; - - /** - * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix - * @param L the lower triangular matrix - * @param D the diagonal matrix - * @param U the upper triangular matrix - * @param a the input matrix to factorize - */ - public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; - - /** - * Adds two mat2's - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static add(out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static subtract (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @returns {mat2} out - */ - public static sub (out: mat2, a: mat2, b: mat2): mat2; - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2, b: mat2): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2} a The first matrix. - * @param {mat2} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2, b: mat2): boolean; - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2} out the receiving matrix - * @param {mat2} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2} out - */ - public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 - - /** - * Adds two mat2's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2} out the receiving vector - * @param {mat2} a the first operand - * @param {mat2} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2} out - */ - public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 - - - -} - -// mat2d -export class mat2d extends Float32Array { - private typeMat2d: number; - - /** - * Creates a new identity mat2d - * - * @returns a new 2x3 matrix - */ - public static create(): mat2d; - - /** - * Creates a new mat2d initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 2x3 matrix - */ - public static clone(a: mat2d): mat2d; - - /** - * Copy the values from one mat2d to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat2d, a: mat2d): mat2d; - - /** - * Set a mat2d to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat2d): mat2d; - - /** - * Create a new mat2d with the given values - * - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} A new mat2d - */ - public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - - /** - * Set the components of a mat2d to the given values - * - * @param {mat2d} out the receiving matrix - * @param {number} a Component A (index 0) - * @param {number} b Component B (index 1) - * @param {number} c Component C (index 2) - * @param {number} d Component D (index 3) - * @param {number} tx Component TX (index 4) - * @param {number} ty Component TY (index 5) - * @returns {mat2d} out - */ - public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d - - /** - * Inverts a mat2d - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat2d, a: mat2d): mat2d; - - /** - * Calculates the determinant of a mat2d - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat2d): number; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Multiplies two mat2d's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; - - /** - * Rotates a mat2d by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; - - /** - * Scales the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Translates the mat2d by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v the vec2 to translate the matrix by - * @returns out - **/ - public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.rotate(dest, dest, rad); - * - * @param {mat2d} out mat2d receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat2d} out - */ - public static fromRotation (out: mat2d, rad: number): mat2d; - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.scale(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat2d} out - */ - public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat2d.identity(dest); - * mat2d.translate(dest, dest, vec); - * - * @param {mat2d} out mat2d receiving operation result - * @param {vec2} v Translation vector - * @returns {mat2d} out - */ - public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d - - /** - * Returns a string representation of a mat2d - * - * @param a matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(a: mat2d): string; - - /** - * Returns Frobenius norm of a mat2d - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat2d): number; - - /** - * Adds two mat2d's - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static add (out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Subtracts matrix b from matrix a - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @returns {mat2d} out - */ - public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat2d} out the receiving matrix - * @param {mat2d} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat2d} out - */ - public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; - - /** - * Adds two mat2d's after multiplying each element of the second operand by a scalar value. - * - * @param {mat2d} out the receiving vector - * @param {mat2d} a the first operand - * @param {mat2d} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat2d} out - */ - public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat2d, b: mat2d): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat2d} a The first matrix. - * @param {mat2d} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat2d, b: mat2d): boolean -} - -// mat3 -export class mat3 extends Float32Array { - private typeMat3: number; - - /** - * Creates a new identity mat3 - * - * @returns a new 3x3 matrix - */ - public static create(): mat3; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param {mat3} out the receiving 3x3 matrix - * @param {mat4} a the source 4x4 matrix - * @returns {mat3} out - */ - public static fromMat4(out: mat3, a: mat4): mat3 - - /** - * Creates a new mat3 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 3x3 matrix - */ - public static clone(a: mat3): mat3; - - /** - * Copy the values from one mat3 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat3, a: mat3): mat3; - - /** - * Create a new mat3 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} A new mat3 - */ - public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; - - - /** - * Set the components of a mat3 to the given values - * - * @param {mat3} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m10 Component in column 1, row 0 position (index 3) - * @param {number} m11 Component in column 1, row 1 position (index 4) - * @param {number} m12 Component in column 1, row 2 position (index 5) - * @param {number} m20 Component in column 2, row 0 position (index 6) - * @param {number} m21 Component in column 2, row 1 position (index 7) - * @param {number} m22 Component in column 2, row 2 position (index 8) - * @returns {mat3} out - */ - public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 - - /** - * Set a mat3 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat3): mat3; - - /** - * Transpose the values of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat3, a: mat3): mat3; - - /** - * Inverts a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat3, a: mat3): mat3; - - /** - * Calculates the adjugate of a mat3 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat3, a: mat3): mat3; - - /** - * Calculates the determinant of a mat3 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat3): number; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat3, a: mat3, b: mat3): mat3; - - /** - * Multiplies two mat3's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat3, a: mat3, b: mat3): mat3; - - - /** - * Translate a mat3 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; - - /** - * Rotates a mat3 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotate(out: mat3, a: mat3, rad: number): mat3; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.translate(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Translation vector - * @returns {mat3} out - */ - public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 - - /** - * Creates a matrix from a given angle - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.rotate(dest, dest, rad); - * - * @param {mat3} out mat3 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat3} out - */ - public static fromRotation(out: mat3, rad: number): mat3 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat3.identity(dest); - * mat3.scale(dest, dest, vec); - * - * @param {mat3} out mat3 receiving operation result - * @param {vec2} v Scaling vector - * @returns {mat3} out - */ - public static fromScaling(out: mat3, v: vec2 | number[]): mat3 - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - public static fromMat2d(out: mat3, a: mat2d): mat3; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - public static fromQuat(out: mat3, q: quat): mat3; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - public static normalFromMat4(out: mat3, a: mat4): mat3; - - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat3): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat3): number; - - /** - * Adds two mat3's - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static add(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static subtract(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @returns {mat3} out - */ - public static sub(out: mat3, a: mat3, b: mat3): mat3 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat3} out the receiving matrix - * @param {mat3} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat3} out - */ - public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 - - /** - * Adds two mat3's after multiplying each element of the second operand by a scalar value. - * - * @param {mat3} out the receiving vector - * @param {mat3} a the first operand - * @param {mat3} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat3} out - */ - public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals(a: mat3, b: mat3): boolean; - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat3} a The first matrix. - * @param {mat3} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals(a: mat3, b: mat3): boolean -} - -// mat4 -export class mat4 extends Float32Array { - private typeMat4: number; - - /** - * Creates a new identity mat4 - * - * @returns a new 4x4 matrix - */ - public static create(): mat4; - - /** - * Creates a new mat4 initialized with values from an existing matrix - * - * @param a matrix to clone - * @returns a new 4x4 matrix - */ - public static clone(a: mat4): mat4; - - /** - * Copy the values from one mat4 to another - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static copy(out: mat4, a: mat4): mat4; - - - /** - * Create a new mat4 with the given values - * - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} A new mat4 - */ - public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set the components of a mat4 to the given values - * - * @param {mat4} out the receiving matrix - * @param {number} m00 Component in column 0, row 0 position (index 0) - * @param {number} m01 Component in column 0, row 1 position (index 1) - * @param {number} m02 Component in column 0, row 2 position (index 2) - * @param {number} m03 Component in column 0, row 3 position (index 3) - * @param {number} m10 Component in column 1, row 0 position (index 4) - * @param {number} m11 Component in column 1, row 1 position (index 5) - * @param {number} m12 Component in column 1, row 2 position (index 6) - * @param {number} m13 Component in column 1, row 3 position (index 7) - * @param {number} m20 Component in column 2, row 0 position (index 8) - * @param {number} m21 Component in column 2, row 1 position (index 9) - * @param {number} m22 Component in column 2, row 2 position (index 10) - * @param {number} m23 Component in column 2, row 3 position (index 11) - * @param {number} m30 Component in column 3, row 0 position (index 12) - * @param {number} m31 Component in column 3, row 1 position (index 13) - * @param {number} m32 Component in column 3, row 2 position (index 14) - * @param {number} m33 Component in column 3, row 3 position (index 15) - * @returns {mat4} out - */ - public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; - - /** - * Set a mat4 to the identity matrix - * - * @param out the receiving matrix - * @returns out - */ - public static identity(out: mat4): mat4; - - /** - * Transpose the values of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static transpose(out: mat4, a: mat4): mat4; - - /** - * Inverts a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static invert(out: mat4, a: mat4): mat4; - - /** - * Calculates the adjugate of a mat4 - * - * @param out the receiving matrix - * @param a the source matrix - * @returns out - */ - public static adjoint(out: mat4, a: mat4): mat4; - - /** - * Calculates the determinant of a mat4 - * - * @param a the source matrix - * @returns determinant of a - */ - public static determinant(a: mat4): number; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Multiplies two mat4's - * - * @param out the receiving matrix - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: mat4, a: mat4, b: mat4): mat4; - - /** - * Translate a mat4 by the given vector - * - * @param out the receiving matrix - * @param a the matrix to translate - * @param v vector to translate by - * @returns out - */ - public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Scales the mat4 by the dimensions in the given vec3 - * - * @param out the receiving matrix - * @param a the matrix to scale - * @param v the vec3 to scale the matrix by - * @returns out - **/ - public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; - - /** - * Rotates a mat4 by the given angle - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @param axis the axis to rotate around - * @returns out - */ - public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; - - /** - * Rotates a matrix by the given angle around the X axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateX(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Y axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateY(out: mat4, a: mat4, rad: number): mat4; - - /** - * Rotates a matrix by the given angle around the Z axis - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param rad the angle to rotate the matrix by - * @returns out - */ - public static rotateZ(out: mat4, a: mat4, rad: number): mat4; - - /** - * Creates a matrix from a vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Translation vector - * @returns {mat4} out - */ - public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a vector scaling - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.scale(dest, dest, vec); - * - * @param {mat4} out mat4 receiving operation result - * @param {vec3} v Scaling vector - * @returns {mat4} out - */ - public static fromScaling(out: mat4, v: vec3 | number[]): mat4 - - /** - * Creates a matrix from a given angle around a given axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotate(dest, dest, rad, axis); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @param {vec3} axis the axis to rotate around - * @returns {mat4} out - */ - public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 - - /** - * Creates a matrix from the given angle around the X axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateX(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromXRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from the given angle around the Y axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateY(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromYRotation(out: mat4, rad: number): mat4 - - - /** - * Creates a matrix from the given angle around the Z axis - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.rotateZ(dest, dest, rad); - * - * @param {mat4} out mat4 receiving operation result - * @param {number} rad the angle to rotate the matrix by - * @returns {mat4} out - */ - public static fromZRotation(out: mat4, rad: number): mat4 - - /** - * Creates a matrix from a quaternion rotation and vector translation - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @returns out - */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; - - /** - * Returns the translation vector component of a transformation - * matrix. If a matrix is built with fromRotationTranslation, - * the returned vector will be the same as the translation vector - * originally supplied. - * @param {vec3} out Vector to receive translation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {vec3} out - */ - public static getTranslation(out: vec3, mat: mat4): vec3; - - /** - * Returns a quaternion representing the rotational component - * of a transformation matrix. If a matrix is built with - * fromRotationTranslation, the returned quaternion will be the - * same as the quaternion originally supplied. - * @param {quat} out Quaternion to receive the rotation component - * @param {mat4} mat Matrix to be decomposed (input) - * @return {quat} out - */ - public static getRotation(out: quat, mat: mat4): quat; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @param s Scaling vector - * @returns out - */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * mat4.translate(dest, origin); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * mat4.translate(dest, negativeOrigin); - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Rotation quaternion - * @param {vec3} v Translation vector - * @param {vec3} s Scaling vector - * @param {vec3} o The origin vector around which to scale and rotate - * @returns {mat4} out - */ - public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 - - /** - * Calculates a 4x4 matrix from the given quaternion - * - * @param {mat4} out mat4 receiving operation result - * @param {quat} q Quaternion to create matrix from - * - * @returns {mat4} out - */ - public static fromQuat(out: mat4, q: quat): mat4 - - /** - * Generates a frustum matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static frustum(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static perspective(out: mat4, fovy: number, aspect: number, - near: number, far: number): mat4; - - /** - * Generates a perspective projection matrix with the given field of view. - * This is primarily useful for generating projection matrices to be used - * with the still experimental WebVR API. - * - * @param {mat4} out mat4 frustum matrix will be written into - * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees - * @param {number} near Near bound of the frustum - * @param {number} far Far bound of the frustum - * @returns {mat4} out - */ - public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, - near: number, far: number): mat4 - - /** - * Generates a orthogonal projection matrix with the given bounds - * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out - */ - public static ortho(out: mat4, left: number, right: number, - bottom: number, top: number, near: number, far: number): mat4; - - /** - * Generates a look-at matrix with the given eye position, focal point, and up axis - * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out - */ - public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; - - /** - * Returns a string representation of a mat4 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - public static str(mat: mat4): string; - - /** - * Returns Frobenius norm of a mat4 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - public static frob(a: mat4): number; - - /** - * Adds two mat4's - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static add(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static subtract(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Subtracts matrix b from matrix a - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @returns {mat4} out - */ - public static sub(out: mat4, a: mat4, b: mat4): mat4 - - /** - * Multiply each element of the matrix by a scalar. - * - * @param {mat4} out the receiving matrix - * @param {mat4} a the matrix to scale - * @param {number} b amount to scale the matrix's elements by - * @returns {mat4} out - */ - public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 - - /** - * Adds two mat4's after multiplying each element of the second operand by a scalar value. - * - * @param {mat4} out the receiving vector - * @param {mat4} a the first operand - * @param {mat4} b the second operand - * @param {number} scale the amount to scale b's elements by before adding - * @returns {mat4} out - */ - public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 - - /** - * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static exactEquals (a: mat4, b: mat4): boolean - - /** - * Returns whether or not the matrices have approximately the same elements in the same position. - * - * @param {mat4} a The first matrix. - * @param {mat4} b The second matrix. - * @returns {boolean} True if the matrices are equal, false otherwise. - */ - public static equals (a: mat4, b: mat4): boolean - -} - -// quat -export class quat extends Float32Array { - private typeQuat: number; - - /** - * Creates a new identity quat - * - * @returns a new quaternion - */ - public static create(): quat; - - /** - * Creates a new quat initialized with values from an existing quaternion - * - * @param a quaternion to clone - * @returns a new quaternion - * @function - */ - public static clone(a: quat): quat; - - /** - * Creates a new quat initialized with the given values - * - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns a new quaternion - * @function - */ - public static fromValues(x: number, y: number, z: number, w: number): quat; - - /** - * Copy the values from one quat to another - * - * @param out the receiving quaternion - * @param a the source quaternion - * @returns out - * @function - */ - public static copy(out: quat, a: quat): quat; - - /** - * Set the components of a quat to the given values - * - * @param out the receiving quaternion - * @param x X component - * @param y Y component - * @param z Z component - * @param w W component - * @returns out - * @function - */ - public static set(out: quat, x: number, y: number, z: number, w: number): quat; - - /** - * Set a quat to the identity quaternion - * - * @param out the receiving quaternion - * @returns out - */ - public static identity(out: quat): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param {quat} out the receiving quaternion. - * @param {vec3} a the initial vector - * @param {vec3} b the destination vector - * @returns {quat} out - */ - public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param {vec3} view the vector representing the viewing direction - * @param {vec3} right the vector representing the local "right" direction - * @param {vec3} up the vector representing the local "up" direction - * @returns {quat} out - */ - public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat - - - - /** - * Sets a quat from the given angle and rotation axis, - * then returns it. - * - * @param out the receiving quaternion - * @param axis the axis around which to rotate - * @param rad the angle in radians - * @returns out - **/ - public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; - - /** - * Gets the rotation axis and angle for a given - * quaternion. If a quaternion is created with - * setAxisAngle, this method will return the same - * values as providied in the original parameter list - * OR functionally equivalent values. - * Example: The quaternion formed by axis [0, 0, 1] and - * angle -90 is the same as the quaternion formed by - * [0, 0, 1] and 270. This method favors the latter. - * @param {vec3} out_axis Vector receiving the axis of rotation - * @param {quat} q Quaternion to be decomposed - * @return {number} Angle, in radians, of the rotation - */ - public static getAxisAngle (out_axis: vec3 | number[], q: quat): number - - /** - * Adds two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - * @function - */ - public static add(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static multiply(out: quat, a: quat, b: quat): quat; - - /** - * Multiplies two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @returns out - */ - public static mul(out: quat, a: quat, b: quat): quat; - - /** - * Scales a quat by a scalar number - * - * @param out the receiving vector - * @param a the vector to scale - * @param b amount to scale the vector by - * @returns out - * @function - */ - public static scale(out: quat, a: quat, b: number): quat; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static length(a: quat): number; - - /** - * Calculates the length of a quat - * - * @param a vector to calculate length of - * @returns length of a - * @function - */ - public static len(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static squaredLength(a: quat): number; - - /** - * Calculates the squared length of a quat - * - * @param a vector to calculate squared length of - * @returns squared length of a - * @function - */ - public static sqrLen(a: quat): number; - - /** - * Normalize a quat - * - * @param out the receiving quaternion - * @param a quaternion to normalize - * @returns out - * @function - */ - public static normalize(out: quat, a: quat): quat; - - /** - * Calculates the dot product of two quat's - * - * @param a the first operand - * @param b the second operand - * @returns dot product of a and b - * @function - */ - public static dot(a: quat, b: quat): number; - - /** - * Performs a linear interpolation between two quat's - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - * @function - */ - public static lerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation between two quat - * - * @param out the receiving quaternion - * @param a the first operand - * @param b the second operand - * @param t interpolation amount between the two inputs - * @returns out - */ - public static slerp(out: quat, a: quat, b: quat, t: number): quat; - - /** - * Performs a spherical linear interpolation with two control points - * - * @param {quat} out the receiving quaternion - * @param {quat} a the first operand - * @param {quat} b the second operand - * @param {quat} c the third operand - * @param {quat} d the fourth operand - * @param {number} t interpolation amount - * @returns {quat} out - */ - public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; - - /** - * Calculates the inverse of a quat - * - * @param out the receiving quaternion - * @param a quat to calculate inverse of - * @returns out - */ - public static invert(out: quat, a: quat): quat; - - /** - * Calculates the conjugate of a quat - * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. - * - * @param out the receiving quaternion - * @param a quat to calculate conjugate of - * @returns out - */ - public static conjugate(out: quat, a: quat): quat; - - /** - * Returns a string representation of a quaternion - * - * @param a quat to represent as a string - * @returns string representation of the quat - */ - public static str(a: quat): string; - - /** - * Rotates a quaternion by the given angle about the X axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateX(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Y axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateY(out: quat, a: quat, rad: number): quat; - - /** - * Rotates a quaternion by the given angle about the Z axis - * - * @param out quat receiving operation result - * @param a quat to rotate - * @param rad angle (in radians) to rotate - * @returns out - */ - public static rotateZ(out: quat, a: quat, rad: number): quat; - - /** - * Creates a quaternion from the given 3x3 rotation matrix. - * - * NOTE: The resultant quaternion is not normalized, so you should be sure - * to renormalize the quaternion yourself where necessary. - * - * @param out the receiving quaternion - * @param m rotation matrix - * @returns out - * @function - */ - public static fromMat3(out: quat, m: mat3): quat; - - /** - * Sets the specified quaternion with values corresponding to the given - * axes. Each axis is a vec3 and is expected to be unit length and - * perpendicular to all other specified axes. - * - * @param out the receiving quat - * @param view the vector representing the viewing direction - * @param right the vector representing the local "right" direction - * @param up the vector representing the local "up" direction - * @returns out - */ - public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; - - /** - * Sets a quaternion to represent the shortest rotation from one - * vector to another. - * - * Both vectors are assumed to be unit length. - * - * @param out the receiving quaternion. - * @param a the initial vector - * @param b the destination vector - * @returns out - */ - public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; - - /** - * Calculates the W component of a quat from the X, Y, and Z components. - * Assumes that quaternion is 1 unit in length. - * Any existing W component will be ignored. - * - * @param out the receiving quaternion - * @param a quat to calculate W component of - * @returns out - */ - public static calculateW(out: quat, a: quat): quat; - - /** - * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static exactEquals (a: quat, b: quat): boolean; - - /** - * Returns whether or not the quaternions have approximately the same elements in the same position. - * - * @param {quat} a The first vector. - * @param {quat} b The second vector. - * @returns {boolean} True if the quaternions are equal, false otherwise. - */ - public static equals (a: quat, b: quat): boolean; -} diff --git a/gl-matrix/gl-matrix.d.ts b/gl-matrix/gl-matrix.d.ts index 16366f263a..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix.d.ts +++ b/gl-matrix/gl-matrix.d.ts @@ -1,36 +1,18 @@ // Type definitions for gl-matrix 2.2.2 // Project: https://github.com/toji/gl-matrix -// Definitions by: Tat +// Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace GLM { - interface IArray - { - /** - * Must be indexable like an array - */ - [index: number]: number; - } -} - -// Common -declare namespace glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - export function toRadian(a: number): number; -} - // vec2 -declare namespace vec2 { +export class vec2 extends Float32Array { + private typeVec2: number; + /** * Creates a new, empty vec2 * * @returns a new 2D vector */ - export function create(): GLM.IArray; + public static create(): vec2; /** * Creates a new vec2 initialized with values from an existing vector @@ -38,7 +20,7 @@ declare namespace vec2 { * @param a a vector to clone * @returns a new 2D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -47,7 +29,7 @@ declare namespace vec2 { * @param y Y component * @returns a new 2D vector */ - export function fromValues(x: number, y: number): GLM.IArray; + public static fromValues(x: number, y: number): vec2; /** * Copy the values from one vec2 to another @@ -56,7 +38,7 @@ declare namespace vec2 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -66,7 +48,7 @@ declare namespace vec2 { * @param y Y component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + public static set(out: vec2, x: number, y: number): vec2; /** * Adds two vec2's @@ -76,7 +58,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -86,7 +68,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -96,7 +78,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -106,7 +88,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -116,7 +98,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -126,7 +108,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -136,7 +118,25 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out: vec2, a: vec2 | number[]): vec2; + + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out: vec2, a: vec2 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,17 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; + + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out: vec2, a: vec2 | number[]): vec2; + /** * Scales a vec2 by a scalar number @@ -166,7 +176,7 @@ declare namespace vec2 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -177,7 +187,7 @@ declare namespace vec2 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -186,7 +196,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -195,7 +205,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -204,7 +214,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -213,7 +223,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -221,7 +231,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -229,7 +239,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -237,7 +247,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -245,7 +255,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -254,7 +264,7 @@ declare namespace vec2 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -263,7 +273,7 @@ declare namespace vec2 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -272,7 +282,7 @@ declare namespace vec2 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -281,7 +291,7 @@ declare namespace vec2 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -292,7 +302,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -303,7 +313,7 @@ declare namespace vec2 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -311,7 +321,7 @@ declare namespace vec2 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec2): vec2; /** * Generates a random vector with the given scale @@ -320,7 +330,7 @@ declare namespace vec2 { * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec2, scale: number): vec2; /** * Transforms the vec2 with a mat2 @@ -330,7 +340,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -340,7 +350,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -351,7 +361,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -363,7 +373,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -376,8 +386,8 @@ declare namespace vec2 { * @param arg additional argument to pass to fn * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -389,27 +399,46 @@ declare namespace vec2 { * @param fn Function to call for each vector in the array * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec2 | number[]): string; + + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; } // vec3 -declare namespace vec3 { +export class vec3 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec3 * * @returns a new 3D vector */ - export function create(): GLM.IArray; + public static create(): vec3; /** * Creates a new vec3 initialized with values from an existing vector @@ -417,7 +446,7 @@ declare namespace vec3 { * @param a vector to clone * @returns a new 3D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -427,7 +456,7 @@ declare namespace vec3 { * @param z Z component * @returns a new 3D vector */ - export function fromValues(x: number, y: number, z: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number): vec3; /** * Copy the values from one vec3 to another @@ -436,7 +465,7 @@ declare namespace vec3 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -447,7 +476,7 @@ declare namespace vec3 { * @param z Z component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + public static set(out: vec3, x: number, y: number, z: number): vec3; /** * Adds two vec3's @@ -457,7 +486,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -467,7 +496,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -477,7 +506,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -487,7 +516,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -497,7 +526,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -507,7 +536,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -517,7 +546,25 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out: vec3, a: vec3 | number[]): vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out: vec3, a: vec3 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -527,7 +574,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -537,7 +584,16 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out: vec3, a: vec3 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -547,7 +603,7 @@ declare namespace vec3 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -558,7 +614,7 @@ declare namespace vec3 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -567,7 +623,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -576,7 +632,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -585,7 +641,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -594,7 +650,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -602,7 +658,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -610,7 +666,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -618,7 +674,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -626,7 +682,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -635,7 +691,7 @@ declare namespace vec3 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -644,7 +700,7 @@ declare namespace vec3 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -653,7 +709,7 @@ declare namespace vec3 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -662,7 +718,7 @@ declare namespace vec3 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -672,7 +728,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -683,7 +739,33 @@ declare namespace vec3 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -691,46 +773,16 @@ declare namespace vec3 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec3): vec3; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param [scale] Length of the resulting vector. If ommitted, a unit vector will be returned + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; - - /** - * Rotate a 3D vector around the x-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * Rotate a 3D vector around the y-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * Rotate a 3D vector around the z-axis - * @param out The receiving vec3 - * @param a The vec3 point to rotate - * @param b The origin of the rotation - * @param c The angle of rotation - * @returns out - */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + public static random(out: vec3, scale: number): vec3; /** * Transforms the vec3 with a mat3. @@ -740,7 +792,7 @@ declare namespace vec3 { * @param m the 3x3 matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -751,9 +803,9 @@ declare namespace vec3 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - /** + /** * Transforms the vec3 with a quat * * @param out the receiving vector @@ -761,9 +813,39 @@ declare namespace vec3 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; + /** * Perform some operation over an array of vec3s. * @@ -776,8 +858,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -790,8 +872,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -799,26 +881,45 @@ declare namespace vec3 { * @param b The second operand * @returns The angle in radians */ - export function angle(a: GLM.IArray, b: GLM.IArray): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec3 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean } // vec4 -declare namespace vec4 { +export class vec4 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec4 * * @returns a new 4D vector */ - export function create(): GLM.IArray; + public static create(): vec4; /** * Creates a new vec4 initialized with values from an existing vector @@ -826,7 +927,7 @@ declare namespace vec4 { * @param a vector to clone * @returns a new 4D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -837,7 +938,7 @@ declare namespace vec4 { * @param w W component * @returns a new 4D vector */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): vec4; /** * Copy the values from one vec4 to another @@ -846,7 +947,7 @@ declare namespace vec4 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -858,7 +959,7 @@ declare namespace vec4 { * @param w W component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; /** * Adds two vec4's @@ -868,7 +969,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -878,7 +979,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -888,7 +989,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -898,7 +999,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -908,7 +1009,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -918,7 +1019,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -928,7 +1029,25 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out: vec4, a: vec4 | number[]): vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out: vec4, a: vec4 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -938,7 +1057,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -948,7 +1067,16 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out: vec4, a: vec4 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -958,7 +1086,7 @@ declare namespace vec4 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -969,7 +1097,7 @@ declare namespace vec4 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -978,7 +1106,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -987,7 +1115,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -996,7 +1124,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1005,7 +1133,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1013,7 +1141,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1021,7 +1149,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1029,7 +1157,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1037,7 +1165,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1046,7 +1174,7 @@ declare namespace vec4 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1055,7 +1183,7 @@ declare namespace vec4 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1064,7 +1192,7 @@ declare namespace vec4 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1073,7 +1201,7 @@ declare namespace vec4 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1084,7 +1212,7 @@ declare namespace vec4 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1092,16 +1220,16 @@ declare namespace vec4 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec4): vec4; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec4, scale: number): vec4; /** * Transforms the vec4 with a mat4. @@ -1111,7 +1239,7 @@ declare namespace vec4 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1121,7 +1249,8 @@ declare namespace vec4 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1131,12 +1260,12 @@ declare namespace vec4 { * @param offset Number of elements to skip at the beginning of the array * @param count Number of vec4s to iterate over. If 0 iterates over entire array * @param fn Function to call for each vector in the array - * @param additional argument to pass to fn + * @param arg additional argument to pass to fn * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1149,27 +1278,46 @@ declare namespace vec4 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec4 | number[]): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; } // mat2 -declare namespace mat2 { +export class mat2 extends Float32Array { + private typeMat2: number; /** * Creates a new identity mat2 * * @returns a new 2x2 matrix */ - export function create(): GLM.IArray; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1177,7 +1325,7 @@ declare namespace mat2 { * @param a matrix to clone * @returns a new 2x2 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1186,7 +1334,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1194,7 +1342,30 @@ declare namespace mat2 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat2): mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; /** * Transpose the values of a mat2 @@ -1203,7 +1374,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1212,7 +1383,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1221,7 +1392,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1229,7 +1400,7 @@ declare namespace mat2 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1239,7 +1410,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1249,7 +1420,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1259,7 +1430,7 @@ declare namespace mat2 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1269,7 +1440,33 @@ declare namespace mat2 { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out: mat2, rad: number): mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1277,7 +1474,7 @@ declare namespace mat2 { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1285,7 +1482,7 @@ declare namespace mat2 { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1294,18 +1491,91 @@ declare namespace mat2 { * @param U the upper triangular matrix * @param a the input matrix to factorize */ - export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out: mat2, a: mat2, b: mat2): mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2, b: mat2): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2, b: mat2): boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out: mat2, a: mat2, b: number): mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 + + + } // mat2d -declare namespace mat2d { +export class mat2d extends Float32Array { + private typeMat2d: number; /** * Creates a new identity mat2d * * @returns a new 2x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat2d; /** * Creates a new mat2d initialized with values from an existing matrix @@ -1313,7 +1583,7 @@ declare namespace mat2d { * @param a matrix to clone * @returns a new 2x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2d): mat2d; /** * Copy the values from one mat2d to another @@ -1322,7 +1592,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2d, a: mat2d): mat2d; /** * Set a mat2d to the identity matrix @@ -1330,7 +1600,35 @@ declare namespace mat2d { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** * Inverts a mat2d @@ -1339,7 +1637,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2d, a: mat2d): mat2d; /** * Calculates the determinant of a mat2d @@ -1347,7 +1645,7 @@ declare namespace mat2d { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2d): number; /** * Multiplies two mat2d's @@ -1357,7 +1655,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Multiplies two mat2d's @@ -1367,7 +1665,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Rotates a mat2d by the given angle @@ -1377,7 +1675,7 @@ declare namespace mat2d { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; /** * Scales the mat2d by the dimensions in the given vec2 @@ -1387,7 +1685,7 @@ declare namespace mat2d { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1397,7 +1695,46 @@ declare namespace mat2d { * @param v the vec2 to translate the matrix by * @returns out **/ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out: mat2d, rad: number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1405,7 +1742,7 @@ declare namespace mat2d { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2d): string; /** * Returns Frobenius norm of a mat2d @@ -1413,18 +1750,97 @@ declare namespace mat2d { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale: number): mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean } // mat3 -declare namespace mat3 { +export class mat3 extends Float32Array { + private typeMat3: number; /** * Creates a new identity mat3 * * @returns a new 3x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out: mat3, a: mat4): mat3 /** * Creates a new mat3 initialized with values from an existing matrix @@ -1432,7 +1848,7 @@ declare namespace mat3 { * @param a matrix to clone * @returns a new 3x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1441,7 +1857,41 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat3, a: mat3): mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out: mat3, m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3 /** * Set a mat3 to the identity matrix @@ -1449,7 +1899,7 @@ declare namespace mat3 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1458,7 +1908,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1467,7 +1917,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1476,7 +1926,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1484,7 +1934,7 @@ declare namespace mat3 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1494,7 +1944,7 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1504,71 +1954,8 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat3, a: mat3, b: mat3): mat3; - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - export function str(mat: GLM.IArray): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - export function frob(a: GLM.IArray): number; - - /** - * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix - * - * @param out mat3 receiving operation result - * @param a Mat4 to derive the normal matrix from - * - * @returns out - */ - export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param out the receiving 3x3 matrix - * @param a the source 4x4 matrix - * @returns out - */ - export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Scales the mat3 by the dimensions in the given vec2 - * - * @param out the receiving matrix - * @param a the matrix to rotate - * @param v the vec2 to scale the matrix by - * @returns out - **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; /** * Translate a mat3 by the given vector @@ -1578,7 +1965,7 @@ declare namespace mat3 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1588,18 +1975,182 @@ declare namespace mat3 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat3, a: mat3, rad: number): mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out: mat3, rad: number): mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out: mat3, a: mat2d): mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out: mat3, q: quat): mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out: mat3, a: mat4): mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat3): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat3): number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out: mat3, a: mat3, b: mat3): mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out: mat3, a: mat3, b: number): mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out: mat3, a: mat3, b: mat3, scale: number): mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a: mat3, b: mat3): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a: mat3, b: mat3): boolean } // mat4 -declare namespace mat4 { +export class mat4 extends Float32Array { + private typeMat4: number; /** * Creates a new identity mat4 * * @returns a new 4x4 matrix */ - export function create(): GLM.IArray; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -1607,7 +2158,7 @@ declare namespace mat4 { * @param a matrix to clone * @returns a new 4x4 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -1616,7 +2167,55 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat4, a: mat4): mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out: mat4, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number): mat4; /** * Set a mat4 to the identity matrix @@ -1624,7 +2223,7 @@ declare namespace mat4 { * @param out the receiving matrix * @returns out */ - export function identity(a: GLM.IArray): GLM.IArray; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -1633,7 +2232,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -1642,7 +2241,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -1651,7 +2250,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -1659,7 +2258,7 @@ declare namespace mat4 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -1669,7 +2268,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -1679,7 +2278,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -1689,7 +2288,7 @@ declare namespace mat4 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -1699,7 +2298,7 @@ declare namespace mat4 { * @param v the vec3 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -1710,7 +2309,7 @@ declare namespace mat4 { * @param axis the axis to rotate around * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -1720,7 +2319,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -1730,7 +2329,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -1740,78 +2339,87 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** - * Generates a frustum matrix with the given bounds + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out */ - export function frustum(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a perspective projection matrix with the given bounds + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param fovy Vertical field of view in radians - * @param aspect Aspect ratio. typically viewport width/height - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out */ - export function perspective(out: GLM.IArray, fovy: number, aspect: number, - near: number, far: number): GLM.IArray; + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a orthogonal projection matrix with the given bounds + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param left Left bound of the frustum - * @param right Right bound of the frustum - * @param bottom Bottom bound of the frustum - * @param top Top bound of the frustum - * @param near Near bound of the frustum - * @param far Far bound of the frustum - * @returns out + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out */ - export function ortho(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** - * Generates a look-at matrix with the given eye position, focal point, and up axis + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): * - * @param out mat4 frustum matrix will be written into - * @param eye Position of the viewer - * @param center Point the viewer is looking at - * @param up vec3 pointing up - * @returns out + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function lookAt(out: GLM.IArray, eye: GLM.IArray, - center: GLM.IArray, up: GLM.IArray): GLM.IArray; + public static fromXRotation(out: mat4, rad: number): mat4 /** - * Returns a string representation of a mat4 + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): * - * @param mat matrix to represent as a string - * @returns string representation of the matrix + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function str(mat: GLM.IArray): string; + public static fromYRotation(out: mat4, rad: number): mat4 + /** - * Returns Frobenius norm of a mat4 + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out */ - export function frob(a: GLM.IArray): number; + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -1828,47 +2436,247 @@ declare namespace mat4 { * @param v Translation vector * @returns out */ - export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * Creates a matrix from a quaternion rotation, vector translation and vector scale. - * - * This is equivalent to (but much faster than): - * - * mat4.identity(dest); - * mat4.translate(dest, vec); - * var quatMat = mat4.create(); - * quat4.toMat4(quat, quatMat); - * mat4.multiply(dest, quatMat); - * mat4.scale(dest, scale) - * - * @param out mat4 receiving operation result - * @param q Rotation quaternion - * @param v Translation vector - * @param s Scale vector - * @returns out - */ - export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** - * Creates a matrix from a quaternion + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out: vec3, mat: mat4): vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out: quat, mat: mat4): quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) * * @param out mat4 receiving operation result * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector * @returns out */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out: mat4, q: quat): mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out: mat4, fovy: number, aspect: number, + near: number, far: number): mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out: mat4, + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out: mat4, left: number, right: number, + bottom: number, top: number, near: number, far: number): mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat: mat4): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat4): number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out: mat4, a: mat4, b: mat4): mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out: mat4, a: mat4, b: number): mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out: mat4, a: mat4, b: mat4, scale: number): mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat4, b: mat4): boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat4, b: mat4): boolean + } // quat -declare namespace quat { +export class quat extends Float32Array { + private typeQuat: number; /** * Creates a new identity quat * * @returns a new quaternion */ - export function create(): GLM.IArray; + public static create(): quat; /** * Creates a new quat initialized with values from an existing quaternion @@ -1877,7 +2685,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: quat): quat; /** * Creates a new quat initialized with the given values @@ -1889,7 +2697,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): quat; /** * Copy the values from one quat to another @@ -1899,7 +2707,7 @@ declare namespace quat { * @returns out * @function */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: quat, a: quat): quat; /** * Set the components of a quat to the given values @@ -1912,7 +2720,7 @@ declare namespace quat { * @returns out * @function */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: quat, x: number, y: number, z: number, w: number): quat; /** * Set a quat to the identity quaternion @@ -1920,7 +2728,34 @@ declare namespace quat { * @param out the receiving quaternion * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat + + /** * Sets a quat from the given angle and rotation axis, @@ -1931,7 +2766,22 @@ declare namespace quat { * @param rad the angle in radians * @returns out **/ - export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number /** * Adds two quat's @@ -1942,7 +2792,7 @@ declare namespace quat { * @returns out * @function */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1952,7 +2802,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1962,7 +2812,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: quat, a: quat, b: quat): quat; /** * Scales a quat by a scalar number @@ -1973,7 +2823,7 @@ declare namespace quat { * @returns out * @function */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: quat, a: quat, b: number): quat; /** * Calculates the length of a quat @@ -1982,7 +2832,7 @@ declare namespace quat { * @returns length of a * @function */ - export function length(a: GLM.IArray): number; + public static length(a: quat): number; /** * Calculates the length of a quat @@ -1991,7 +2841,7 @@ declare namespace quat { * @returns length of a * @function */ - export function len(a: GLM.IArray): number; + public static len(a: quat): number; /** * Calculates the squared length of a quat @@ -2000,7 +2850,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: quat): number; /** * Calculates the squared length of a quat @@ -2009,7 +2859,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: quat): number; /** * Normalize a quat @@ -2019,7 +2869,7 @@ declare namespace quat { * @returns out * @function */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: quat, a: quat): quat; /** * Calculates the dot product of two quat's @@ -2029,7 +2879,7 @@ declare namespace quat { * @returns dot product of a and b * @function */ - export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: quat, b: quat): number; /** * Performs a linear interpolation between two quat's @@ -2041,7 +2891,7 @@ declare namespace quat { * @returns out * @function */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation between two quat @@ -2052,7 +2902,20 @@ declare namespace quat { * @param t interpolation amount between the two inputs * @returns out */ - export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static slerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; /** * Calculates the inverse of a quat @@ -2061,7 +2924,7 @@ declare namespace quat { * @param a quat to calculate inverse of * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: quat, a: quat): quat; /** * Calculates the conjugate of a quat @@ -2071,15 +2934,15 @@ declare namespace quat { * @param a quat to calculate conjugate of * @returns out */ - export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static conjugate(out: quat, a: quat): quat; /** - * Returns a string representation of a quatenion + * Returns a string representation of a quaternion * - * @param vec vector to represent as a string - * @returns string representation of the vector + * @param a quat to represent as a string + * @returns string representation of the quat */ - export function str(a: GLM.IArray): string; + public static str(a: quat): string; /** * Rotates a quaternion by the given angle about the X axis @@ -2089,7 +2952,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Y axis @@ -2099,7 +2962,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Z axis @@ -2109,7 +2972,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: quat, a: quat, rad: number): quat; /** * Creates a quaternion from the given 3x3 rotation matrix. @@ -2122,20 +2985,20 @@ declare namespace quat { * @returns out * @function */ - export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static fromMat3(out: quat, m: mat3): quat; /** * Sets the specified quaternion with values corresponding to the given * axes. Each axis is a vec3 and is expected to be unit length and * perpendicular to all other specified axes. * + * @param out the receiving quat * @param view the vector representing the viewing direction * @param right the vector representing the local "right" direction * @param up the vector representing the local "up" direction * @returns out */ - export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, - up: GLM.IArray): GLM.IArray; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -2148,7 +3011,7 @@ declare namespace quat { * @param b the destination vector * @returns out */ - export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -2159,5 +3022,23 @@ declare namespace quat { * @param a quat to calculate W component of * @returns out */ - export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a: quat, b: quat): boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a: quat, b: quat): boolean; } From 6d9768b337310fa80e348ed5da12d0547f5a5a52 Mon Sep 17 00:00:00 2001 From: Stephen Feest Date: Wed, 17 Aug 2016 10:03:38 +0100 Subject: [PATCH 004/154] Add additional $transclude function parameters A couple of additional optional parameters were added to the `$transclude` function when support for multi-slot transclusion was added in Angular 1.5 [1]. This commit updates the `ITranscludeFunction` type definition to reflect those changes. [1] https://docs.angularjs.org/api/ng/service/$compile#-controller- --- angularjs/angular.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3c13fd6cf3..a6a130a66d 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1258,7 +1258,7 @@ declare namespace angular { // This corresponds to $transclude (and also the transclude function passed to link). interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. - (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery; + (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. (cloneAttachFn?: ICloneAttachFunction): JQuery; } From ed50b4775d7d49a44d3d39d103aa4f50d3442174 Mon Sep 17 00:00:00 2001 From: Stephen Feest Date: Wed, 17 Aug 2016 21:35:36 +0100 Subject: [PATCH 005/154] Add $transclude function tests These tests try to exercise the different ways that the $transclude can be called including: + With and without specifying the scope explicitly + With and without a clone attach function + With and without specifying the future parent + Using the default and named transclude slots --- angularjs/angular-tests.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index ef3e29b4c8..07f67a7375 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -867,6 +867,26 @@ angular.module('docsTabsExample', []) }; }); +angular.module('multiSlotTranscludeExample', []) + .directive('dropDownMenu', function() { + return { + transclude: { + button: 'button', + list: 'ul', + }, + link: function(scope, element, attrs, ctrl, transclude) { + // without scope + transclude().appendTo(element); + transclude(clone => clone.appendTo(element)); + + // with scope + transclude(scope, clone => clone.appendTo(element)); + transclude(scope, clone => clone.appendTo(element), element, 'button'); + transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element); + } + }; + }); + angular.module('componentExample', []) .component('counter', { require: {'ctrl': '^ctrl'}, From 7a7510a12d5b1c3c14f45313807c7c1e6092571e Mon Sep 17 00:00:00 2001 From: minodisk Date: Tue, 16 Aug 2016 20:09:18 +0900 Subject: [PATCH 006/154] Format react-router.d.ts --- react-router/react-router.d.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 3fe2538048..41eb1b53ed 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -236,15 +236,15 @@ declare namespace ReactRouter { // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md interface InjectedRouter { - push: (pathOrLoc: H.LocationDescriptor) => void - replace: (pathOrLoc: H.LocationDescriptor) => void - go: (n: number) => void - goBack: () => void - goForward: () => void - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void - createPath(path: H.Path, query?: H.Query): H.Path - createHref(path: H.Path, query?: H.Query): H.Href - isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean + push: (pathOrLoc: H.LocationDescriptor) => void + replace: (pathOrLoc: H.LocationDescriptor) => void + go: (n: number) => void + goBack: () => void + goForward: () => void + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void + createPath(path: H.Path, query?: H.Query): H.Path + createHref(path: H.Path, query?: H.Query): H.Href + isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } function withRouter>(component: C): C @@ -359,7 +359,7 @@ declare module "react-router/lib/useRoutes" { declare module "react-router/lib/PatternUtils" { - export function formatPattern(pattern: string, params: {}): string; + export function formatPattern(pattern: string, params: {}): string; } @@ -419,16 +419,16 @@ declare module "react-router/lib/PropTypes" { } declare module "react-router/lib/browserHistory" { - export default ReactRouter.browserHistory; + export default ReactRouter.browserHistory; } declare module "react-router/lib/hashHistory" { - export default ReactRouter.hashHistory; + export default ReactRouter.hashHistory; } declare module "react-router/lib/match" { - export default ReactRouter.match + export default ReactRouter.match; } @@ -441,11 +441,11 @@ declare module "react-router/lib/useRouterHistory" { } declare module "react-router/lib/createMemoryHistory" { - export default ReactRouter.createMemoryHistory; + export default ReactRouter.createMemoryHistory; } declare module "react-router/lib/withRouter" { - export default ReactRouter.withRouter; + export default ReactRouter.withRouter; } declare module "react-router" { @@ -504,7 +504,7 @@ declare module "react-router" { export type LeaveHook = ReactRouter.LeaveHook export type ParseQueryString = ReactRouter.ParseQueryString export type RedirectFunction = ReactRouter.RedirectFunction - export type RouteComponentProps = ReactRouter.RouteComponentProps; + export type RouteComponentProps = ReactRouter.RouteComponentProps; export type RouteHook = ReactRouter.RouteHook export type StringifyQuery = ReactRouter.StringifyQuery export type RouterListener = ReactRouter.RouterListener From 35324f1700d0658e194785633f9bf95c9d8764e3 Mon Sep 17 00:00:00 2001 From: minodisk Date: Fri, 19 Aug 2016 09:45:19 +0900 Subject: [PATCH 007/154] Add applyRouterMiddleware to react-router --- react-router/react-router.d.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 41eb1b53ed..6d5051f61b 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -88,6 +88,13 @@ declare namespace ReactRouter { function createMemoryHistory(options?: H.HistoryOptions): H.History + interface Middleware { + renderRouterContext: (previous: React.Props<{}>[], props: React.Props<{}>) => React.Props<{}>[] + renderRouteComponent: (previous: React.Props<{}>[], props: React.Props<{}>) => React.Props<{}>[] + } + + function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => React.Props<{}>[] + /* components */ interface RouterProps extends React.Props { @@ -97,6 +104,7 @@ declare namespace ReactRouter { onError?: (error: any) => any onUpdate?: () => any parseQueryString?: ParseQueryString + render?: (renderProps: React.Props<{}>) => React.Props<{}>[] stringifyQuery?: StringifyQuery } interface Router extends React.ComponentClass {} @@ -448,6 +456,10 @@ declare module "react-router/lib/withRouter" { export default ReactRouter.withRouter; } +declare module "react-router/lib/applyRouterMiddleware" { + export default ReactRouter.applyRouterMiddleware; +} + declare module "react-router" { import Router from "react-router/lib/Router" @@ -492,6 +504,8 @@ declare module "react-router" { import withRouter from "react-router/lib/withRouter"; + import applyRouterMiddleware from "react-router/lib/applyRouterMiddleware"; + // PlainRoute is defined in the API documented at: // https://github.com/rackt/react-router/blob/master/docs/API.md // but not included in any of the .../lib modules above. @@ -534,7 +548,8 @@ declare module "react-router" { match, useRouterHistory, createMemoryHistory, - withRouter + withRouter, + applyRouterMiddleware } export default Router From fedccb1e7ad7e2aad3fad61e7de6ef536a8967c5 Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Sat, 20 Aug 2016 10:31:54 +0100 Subject: [PATCH 008/154] RxJS DOM: ajax doesn't return Error, throws instead RxJS DOM does not return AjaxErrorResponse, it throws it. Observable errors are currently not modelled in the typings. --- rx-dom/rx-dom.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rx-dom/rx-dom.d.ts b/rx-dom/rx-dom.d.ts index 5a42810600..e0d4369c60 100644 --- a/rx-dom/rx-dom.d.ts +++ b/rx-dom/rx-dom.d.ts @@ -110,13 +110,13 @@ declare module Rx.DOM { function touchstart(element: Element, selector?:Function, useCapture?:boolean):Rx.Observable; // Ajax - function ajax(url:string):Rx.Observable; - function ajax(settings:AjaxSettings):Rx.Observable; - function get(url:string):Rx.Observable; + function ajax(url:string):Rx.Observable; + function ajax(settings:AjaxSettings):Rx.Observable; + function get(url:string):Rx.Observable; function getJSON(url:string):Rx.Observable; - function post(url:string, body:any):Rx.Observable; + function post(url:string, body:any):Rx.Observable; function jsonpRequest(url:string):Rx.Observable; - function jsonpRequest(settings:JsonpSettings):Rx.Observable; + function jsonpRequest(settings:JsonpSettings):Rx.Observable; // Server-Sent Events function fromEventSource(url:string, openObservable?:Rx.Observer):Rx.Observable; @@ -139,4 +139,4 @@ declare module Rx.DOM { declare module "rx.DOM" { export default Rx.DOM; -} \ No newline at end of file +} From e9fc032fe8a9cf754f2c9b06ab855bfbf837d4e6 Mon Sep 17 00:00:00 2001 From: Massimo Hamilton Date: Tue, 23 Aug 2016 08:52:49 +0100 Subject: [PATCH 009/154] Durandal - Fixes to DialogContext. See below: - Add blockoutOpacity to DialogContext - Mark name of getContext as optional All as per docs here: http://durandaljs.com/documentation/Showing-Message-Boxes-And-Modals.html#dialog-contexts --- durandal/durandal.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 97e1307a0b..1b28ca7bc3 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -690,6 +690,11 @@ declare module 'plugins/dialog' { * @param {object} context The composition context. */ compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void; + + /** + * Opacity of the blockout. The default is 0.6. + */ + blockoutOpacity?: number; } interface Dialog { @@ -728,7 +733,7 @@ declare module 'plugins/dialog' { * @param {string} [name] The name of the context to retrieve. * @returns {DialogContext} True context. */ - export function getContext(name: string): DialogContext; + export function getContext(name?: string): DialogContext; /** * Adds (or replaces) a dialog context. From ab65bec50eba26e1f3039e44a5007dbb52b117da Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Thu, 25 Aug 2016 10:13:39 +0100 Subject: [PATCH 010/154] added AutoScaling --- aws-sdk/aws-sdk.d.ts | 452 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 452 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index cb35f34e97..652365e156 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -49,6 +49,51 @@ declare module "aws-sdk" { stack: string; } + export interface RetryDelayOption { + base?: number; + customBackoff?: (retryCount: number) => number; + } + + export interface Ebs { + snapshotId?: string; + volumeSize?: number; + volumeType?: string; + deleteOnTermination?: boolean; + iops?: number; + encrypted?: boolean; + } + + export interface BlockDeviceMapping { + virtualName?: string; + deviceName: string; + ebs?: Ebs; + noDevice?: boolean; + } + + export interface InstanceMonitoring { + spotPrice?: string; + enabled?: boolean; + } + + export interface Filter { + Name?: string; + Values?: boolean; + } + + export interface StepAdjustment { + scalingAdjustment: number; + metricIntervalLowerBound?: number; + metricIntervalUpperBound?: number; + } + + export interface Tags { + resourceId?: string; + resourceType?: string; + key: string; + value?: string; + propagateAtLaunch?: boolean; + } + export interface Services { autoscaling?: any; cloudformation?: any; @@ -147,6 +192,64 @@ declare module "aws-sdk" { updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; } + export class AutoScaling { + constructor(options?: any); + endpoint: Endpoint; + + attachInstances(params: AutoScaling.AttachInstancesParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancers(params: AutoScaling.AttachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancerTargetGroups(param: AutoScaling.AttachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + completeLifecycleAction(param: AutoScaling.CompleteLifecycleActionParams, callback: (err: AwsError, data: any) => void): void; + createAutoScalingGroup(param: AutoScaling.CreateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + createLaunchConfiguration(param: AutoScaling.CreateLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + createOrUpdateTags(param: AutoScaling.CreateOrUpdateTagsParams, callback: (err: AwsError, data: any) => void): void; + deleteAutoScalingGroup(param: AutoScaling.DeleteAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + deleteLaunchConfiguration(param: AutoScaling.DeleteLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deleteLifecycleHook(param: AutoScaling.DeleteLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + deleteNotificationConfiguration(param: AutoScaling.DeleteNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deletePolicy(param: AutoScaling.DeletePolicyParams, callback: (err: AwsError, data: any) => void): void; + deleteScheduledAction(param: AutoScaling.DeleteScheduledActionParams, callback: (err: AwsError, data: any) => void): void; + deleteTags(param: AutoScaling.DeleteTagsParams, callback: (err: AwsError, data: any) => void): void; + describeAccountLimits(callback: (err: AwsError, data: any) => void): void; + describeAdjustmentTypes(callback: (err: AwsError, data: any) => void): void; + describeAutoScalingGroups(param: AutoScaling.DescribeAutoScalingGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingInstances(param: AutoScaling.DescribeAutoScalingInstancesParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingNotificationTypes(callback: (err: AwsError, data: any) => void): void; + describeLaunchConfigurations(param: AutoScaling.DescribeLaunchConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHooks(param: AutoScaling.DescribeLifecycleHooksParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHookTypes(callback: (err: AwsError, data: any) => void): void; + describeLoadBalancers(param: AutoScaling.DescribeLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + describeLoadBalancerTargetGroups(param: AutoScaling.DescribeLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeMetricCollectionTypes(callback: (err: AwsError, data: any) => void): void; + describeNotificationConfigurations(param: AutoScaling.DescribeNotificationConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describePolicies(param: AutoScaling.DescribePoliciesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingActivities(param: AutoScaling.DescribeScalingActivitiesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingProcessTypes(callback: (err: AwsError, data: any) => void): void; + describeScheduledActions(param: AutoScaling.DescribeScheduledActionsParams, callback: (err: AwsError, data: any) => void): void; + describeTags(param: AutoScaling.DescribeTagsParams, callback: (err: AwsError, data: any) => void): void; + describeTerminationPolicyTypes(callback: (err: AwsError, data: any) => void): void; + detachInstances(param: AutoScaling.DetachInstancesParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancers(param: AutoScaling.DetachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancerTargetGroups(param: AutoScaling.DetachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + disableMetricsCollection(param: AutoScaling.DisableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enableMetricsCollection(param: AutoScaling.EnableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enterStandby(param: AutoScaling.EnterStandbyParams, callback: (err: AwsError, data: any) => void): void; + executePolicy(param: AutoScaling.ExecutePolicyParams, callback: (err: AwsError, data: any) => void): void; + exitStandby(param: AutoScaling.ExitStandbyParams, callback: (err: AwsError, data: any) => void): void; + putLifecycleHook(param: AutoScaling.PutLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + putNotificationConfiguration(param: AutoScaling.PutNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + putScalingPolicy(param: AutoScaling.PutScalingPolicyParams, callback: (err: AwsError, data: any) => void): void; + putScheduledUpdateGroupAction(param: AutoScaling.PutScheduledUpdateGroupActionParams, callback: (err: AwsError, data: any) => void): void; + recordLifecycleActionHeartbeat(params: AutoScaling.RecordLifecycleActionHeartbeatParams, callback: (err: AwsError, data: any) => void): void; + resumeProcesses(params: AutoScaling.ResumeProcessesParams, callback: (err: AwsError, data: any) => void): void; + setDesiredCapacity(params: AutoScaling.SetDesiredCapacityParams, callback: (err: AwsError, data: any) => void): void; + setInstanceHealth(params: AutoScaling.SetInstanceHealthParams, callback: (err: AwsError, data: any) => void): void; + setInstanceProtection(params: AutoScaling.SetInstanceProtectionParams, callback: (err: AwsError, data: any) => void): void; + suspendProcesses(params: AutoScaling.SuspendProcessesParams, callback: (err: AwsError, data: any) => void): void; + terminateInstanceInAutoScalingGroup(params: AutoScaling.TerminateInstanceInAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + updateAutoScalingGroup(params: AutoScaling.UpdateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + } + export class SQS { constructor(options?: any); endpoint: Endpoint; @@ -592,6 +695,355 @@ declare module "aws-sdk" { } } + export module AutoScaling { + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AttachInstancesParams { + autoScalingGroupName: string; + instanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + autoScalingGroupName: string; + loadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + targetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + autoScalingGroupName: string; + lifecycleActionResult: string; + lifecycleHookName: string; + lifecycleActionToken?: string; + instanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + autoScalingGroupName: string; + minSize: number; + maxSize: number; + launchConfigurationName?: string; + instanceId?: string; + desiredCapacity?: number; + defaultCooldown?: number; + availabilityZones?: string[]; + loadBalancerNames?: string[]; + targetGroupARNs?: string[]; + healthCheckType?: string; + healthCheckGracePeriod?: number; + placementGroup?: string; + vPCZoneIdentifier?: string; + terminationPolicies?: string; + newInstancesProtectedFromScaleIn?: boolean; + tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + launchConfigurationName: string; + associatePublicIpAddress?: boolean; + imageId?: string; + keyName?: string; + securityGroups?: string[]; + classicLinkVPCId?: string; + classicLinkVPCSecurityGroups?: string[]; + userData?: string; + instanceId?: string; + instanceType?: string; + kernelId?: string; + ramdiskId?: string; + blockDeviceMappings?: BlockDeviceMapping[]; + instanceMonitoring?: InstanceMonitoring; + spotPrice?: string; + iamInstanceProfile?: string; + ebsOptimized?: boolean; + placementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + autoScalingGroupName: string; + forceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + launchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + autoScalingGroupName: string; + lifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + autoScalingGroupName: string; + topicARN: string; + } + + export interface DeletePolicyParams { + policyName: string; + autoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + autoScalingGroupName: string; + scheduledActionName: string; + } + + export interface DeleteTagsParams { + tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + autoScalingGroupName?: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + instanceIds?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + launchConfigurationNames?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + autoScalingGroupName: string; + lifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + autoScalingGroupName: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + autoScalingGroupName?: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribePoliciesParams { + autoScalingGroupName?: string; + policyNames?: string[]; + policyTypes?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + autoScalingGroupName?: string; + activityIds?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + autoScalingGroupName?: string; + scheduledActionNames?: string[]; + startTime?: Date; + endTime?: Date; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeTagsParams { + filters?: Filter[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DetachInstancesParams { + autoScalingGroupName: string; + shouldDecrementDesiredCapacity: boolean; + instanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + autoScalingGroupName: string; + loadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + autoScalingGroupName: string; + metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + autoScalingGroupName: string; + granularity: string; + metrics?: string[]; + } + + export interface EnterStandbyParams { + autoScalingGroupName: string; + shouldDecrementDesiredCapacity: boolean; + instanceIds?: string[]; + } + + export interface ExecutePolicyParams { + policyName: string; + autoScalingGroupName?: string; + honorCooldown?: boolean; + metricValue?: number; + breachThreshold?: number; + } + + export interface ExitStandbyParams { + autoScalingGroupName: string; + instanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + autoScalingGroupName: string; + lifecycleHookName: string; + lifecycleTransition?: string; + roleARN?: string; + notificationTargetARN?: string; + notificationMetadata?: string; + heartbeatTimeout?: number; + defaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + autoScalingGroupName: string; + notificationTypes: string[]; + topicARN: string; + } + + export interface PutScalingPolicyParams { + autoScalingGroupName: string; + adjustmentType: string; + policyName: string; + policyType?: string; + minAdjustmentStep?: number; + minAdjustmentMagnitude?: number; + scalingAdjustment?: number; + cooldown?: number; + metricAggregationType?: string; + stepAdjustments?: StepAdjustment[]; + estimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + autoScalingGroupName: string; + scheduledActionName: string; + time?: Date; + startTime?: Date; + endTime?: Date; + recurrence?: string; + minSize?: number; + maxSize?: number; + desiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + autoScalingGroupName: string; + lifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + autoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + autoScalingGroupName: string; + desiredCapacity: number; + honorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + healthStatus: string; + instanceId: string; + shouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + autoScalingGroupName: string; + instanceIds: string[]; + protectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + autoScalingGroupName: string; + scalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + instanceId: string; + shouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + autoScalingGroupName: string; + launchConfigurationName: string; + minSize: number; + maxSize: number; + desiredCapacity: number; + defaultCooldown: number; + availabilityZones: string[]; + healthCheckType: string; + healthCheckGracePeriod: number; + placementGroup: string; + vPCZoneIdentifier: string; + terminationPolicies: string[]; + newInstancesProtectedFromScaleIn?: boolean; + } + } + + export module SQS { export interface SqsOptions { From aa7fb007db039fb20f2db6cf104d1c8c27e59ae7 Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Fri, 26 Aug 2016 16:27:49 +0100 Subject: [PATCH 011/154] fixed the property name with upper case letter --- aws-sdk/aws-sdk.d.ts | 354 +++++++++++++++++++++---------------------- 1 file changed, 177 insertions(+), 177 deletions(-) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 652365e156..6f5ced6cd3 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -726,320 +726,320 @@ declare module "aws-sdk" { } export interface AttachInstancesParams { - autoScalingGroupName: string; - instanceIds: string[]; + AutoScalingGroupName: string; + InstanceIds: string[]; } export interface AttachLoadBalancersParams { - autoScalingGroupName: string; - loadBalancerNames: string[]; + AutoScalingGroupName: string; + LoadBalancerNames: string[]; } export interface AttachLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; - targetGroupARNs: string[]; + AutoScalingGroupName: string; + TargetGroupARNs: string[]; } export interface CompleteLifecycleActionParams { - autoScalingGroupName: string; - lifecycleActionResult: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; lifecycleActionToken?: string; - instanceId?: string; + InstanceId?: string; } export interface CreateAutoScalingGroupParams { - autoScalingGroupName: string; - minSize: number; - maxSize: number; - launchConfigurationName?: string; - instanceId?: string; - desiredCapacity?: number; - defaultCooldown?: number; - availabilityZones?: string[]; - loadBalancerNames?: string[]; - targetGroupARNs?: string[]; - healthCheckType?: string; - healthCheckGracePeriod?: number; - placementGroup?: string; - vPCZoneIdentifier?: string; - terminationPolicies?: string; - newInstancesProtectedFromScaleIn?: boolean; - tags?: Tags; + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; } export interface CreateLaunchConfigurationParams { - launchConfigurationName: string; - associatePublicIpAddress?: boolean; - imageId?: string; - keyName?: string; - securityGroups?: string[]; - classicLinkVPCId?: string; - classicLinkVPCSecurityGroups?: string[]; - userData?: string; - instanceId?: string; - instanceType?: string; - kernelId?: string; - ramdiskId?: string; - blockDeviceMappings?: BlockDeviceMapping[]; - instanceMonitoring?: InstanceMonitoring; - spotPrice?: string; - iamInstanceProfile?: string; - ebsOptimized?: boolean; - placementTenancy?: string; + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; } export interface CreateOrUpdateTagsParams { - tags: Tags[]; + Tags: Tags[]; } export interface DeleteAutoScalingGroupParams { - autoScalingGroupName: string; - forceDelete?: boolean; + AutoScalingGroupName: string; + ForceDelete?: boolean; } export interface DeleteLaunchConfigurationParams { - launchConfigurationName: string; + LaunchConfigurationName: string; } export interface DeleteLifecycleHookParams { - autoScalingGroupName: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleHookName: string; } export interface DeleteNotificationConfigurationParams { - autoScalingGroupName: string; - topicARN: string; + AutoScalingGroupName: string; + TopicARN: string; } export interface DeletePolicyParams { - policyName: string; - autoScalingGroupName?: string; + PolicyName: string; + AutoScalingGroupName?: string; } export interface DeleteScheduledActionParams { - autoScalingGroupName: string; - scheduledActionName: string; + AutoScalingGroupName: string; + ScheduledActionName: string; } export interface DeleteTagsParams { - tags: Tags[]; + Tags: Tags[]; } export interface DescribeAutoScalingGroupsParams { - autoScalingGroupName?: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeAutoScalingInstancesParams { - instanceIds?: string[]; - nextToken?: string; - maxRecords?: number; + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLaunchConfigurationsParams { - launchConfigurationNames?: string[]; - nextToken?: string; - maxRecords?: number; + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLifecycleHooksParams { - autoScalingGroupName: string; - lifecycleHookNames?: string[]; + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; } export interface DescribeLoadBalancersParams { - autoScalingGroupName: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeNotificationConfigurationsParams { - autoScalingGroupName?: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribePoliciesParams { - autoScalingGroupName?: string; - policyNames?: string[]; - policyTypes?: string[]; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeScalingActivitiesParams { - autoScalingGroupName?: string; - activityIds?: string[]; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeScheduledActionsParams { - autoScalingGroupName?: string; - scheduledActionNames?: string[]; - startTime?: Date; - endTime?: Date; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; } export interface DescribeTagsParams { - filters?: Filter[]; - nextToken?: string; - maxRecords?: number; + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; } export interface DetachInstancesParams { - autoScalingGroupName: string; - shouldDecrementDesiredCapacity: boolean; - instanceIds?: string[]; + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; } export interface DetachLoadBalancersParams { - autoScalingGroupName: string; - loadBalancerNames: string; + AutoScalingGroupName: string; + LoadBalancerNames: string; } export interface DetachLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; + AutoScalingGroupName: string; TargetGroupARNs: string[]; } export interface DisableMetricsCollectionParams { - autoScalingGroupName: string; - metrics?: string[]; + AutoScalingGroupName: string; + Metrics?: string[]; } export interface EnableMetricsCollectionParams { - autoScalingGroupName: string; - granularity: string; - metrics?: string[]; + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; } export interface EnterStandbyParams { - autoScalingGroupName: string; - shouldDecrementDesiredCapacity: boolean; - instanceIds?: string[]; + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; } export interface ExecutePolicyParams { - policyName: string; - autoScalingGroupName?: string; - honorCooldown?: boolean; - metricValue?: number; - breachThreshold?: number; + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; } export interface ExitStandbyParams { - autoScalingGroupName: string; - instanceIds?: string[]; + AutoScalingGroupName: string; + InstanceIds?: string[]; } export interface PutLifecycleHookParams { - autoScalingGroupName: string; - lifecycleHookName: string; - lifecycleTransition?: string; - roleARN?: string; - notificationTargetARN?: string; - notificationMetadata?: string; - heartbeatTimeout?: number; - defaultResult?: string; + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; } export interface PutNotificationConfigurationParams { - autoScalingGroupName: string; - notificationTypes: string[]; - topicARN: string; + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; } export interface PutScalingPolicyParams { - autoScalingGroupName: string; - adjustmentType: string; - policyName: string; - policyType?: string; - minAdjustmentStep?: number; - minAdjustmentMagnitude?: number; - scalingAdjustment?: number; - cooldown?: number; - metricAggregationType?: string; - stepAdjustments?: StepAdjustment[]; - estimatedInstanceWarmup: number; + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; } export interface PutScheduledUpdateGroupActionParams { - autoScalingGroupName: string; - scheduledActionName: string; - time?: Date; - startTime?: Date; - endTime?: Date; - recurrence?: string; - minSize?: number; - maxSize?: number; - desiredCapacity?: number; + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; } export interface RecordLifecycleActionHeartbeatParams { - autoScalingGroupName: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleHookName: string; LifecycleActionToken?: string; InstanceId?: string; } export interface ResumeProcessesParams { - autoScalingGroupName: string; + AutoScalingGroupName: string; ScalingProcesses?: string[]; } export interface SetDesiredCapacityParams { - autoScalingGroupName: string; - desiredCapacity: number; - honorCooldown?: boolean; + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; } export interface SetInstanceHealthParams { - healthStatus: string; - instanceId: string; - shouldRespectGracePeriod?: boolean; + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; } export interface SetInstanceProtectionParams { - autoScalingGroupName: string; - instanceIds: string[]; - protectedFromScaleIn: boolean; + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; } export interface SuspendProcessesParams { - autoScalingGroupName: string; - scalingProcesses?: string[]; + AutoScalingGroupName: string; + ScalingProcesses?: string[]; } export interface TerminateInstanceInAutoScalingGroupParams { - instanceId: string; - shouldDecrementDesiredCapacity: boolean; + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; } export interface UpdateAutoScalingGroupParams { - autoScalingGroupName: string; - launchConfigurationName: string; - minSize: number; - maxSize: number; - desiredCapacity: number; - defaultCooldown: number; - availabilityZones: string[]; - healthCheckType: string; - healthCheckGracePeriod: number; - placementGroup: string; - vPCZoneIdentifier: string; - terminationPolicies: string[]; - newInstancesProtectedFromScaleIn?: boolean; + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; } } From df2e17b0a951123fa1ba1e8b673073c4aaef25ed Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Fri, 26 Aug 2016 16:31:19 +0100 Subject: [PATCH 012/154] fixed the first letter of the property to be uppecase --- aws-sdk/aws-sdk.d.ts | 714 +++++++++++++++++++++---------------------- 1 file changed, 357 insertions(+), 357 deletions(-) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 6f5ced6cd3..4ed550251b 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -55,24 +55,24 @@ declare module "aws-sdk" { } export interface Ebs { - snapshotId?: string; - volumeSize?: number; - volumeType?: string; - deleteOnTermination?: boolean; - iops?: number; - encrypted?: boolean; + SnapshotId?: string; + VolumeSize?: number; + VolumeType?: string; + DeleteOnTermination?: boolean; + Iops?: number; + Encrypted?: boolean; } export interface BlockDeviceMapping { - virtualName?: string; - deviceName: string; - ebs?: Ebs; - noDevice?: boolean; + VirtualName?: string; + DeviceName: string; + Ebs?: Ebs; + NoDevice?: boolean; } export interface InstanceMonitoring { - spotPrice?: string; - enabled?: boolean; + SpotPrice?: string; + Enabled?: boolean; } export interface Filter { @@ -696,353 +696,353 @@ declare module "aws-sdk" { } export module AutoScaling { - export interface AutoScalingOptions { - params?: any; - endpoint?: string; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: Credentials; - credentials?: Credentials; - credentialProvider?: any; - region?: string; - maxRetries?: number; - maxRedirects?: number; - sslEnabled?: boolean; - paramValidation?: boolean; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - correctClockSkew?: boolean; - s3ForcePathStyle?: boolean; - s3BucketEndpoint?: boolean; - s3DisableBodySigning?: boolean; - retryDelayOptions?: RetryDelayOption; - httpOptions?: HttpOptions; - apiVersion?: string; - apiVersions?: { [serviceName: string]: string }; - logger?: Logger; - systemClockOffset?: number; - signatureVersion?: string; - signatureCache?: boolean; - } - - export interface AttachInstancesParams { - AutoScalingGroupName: string; - InstanceIds: string[]; - } - - export interface AttachLoadBalancersParams { - AutoScalingGroupName: string; - LoadBalancerNames: string[]; - } - - export interface AttachLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - TargetGroupARNs: string[]; - } - - export interface CompleteLifecycleActionParams { - AutoScalingGroupName: string; - LifecycleActionResult: string; - LifecycleHookName: string; - lifecycleActionToken?: string; - InstanceId?: string; - } - - export interface CreateAutoScalingGroupParams { - AutoScalingGroupName: string; - MinSize: number; - MaxSize: number; - LaunchConfigurationName?: string; - InstanceId?: string; - DesiredCapacity?: number; - DefaultCooldown?: number; - AvailabilityZones?: string[]; - LoadBalancerNames?: string[]; - TargetGroupARNs?: string[]; - HealthCheckType?: string; - HealthCheckGracePeriod?: number; - PlacementGroup?: string; - VPCZoneIdentifier?: string; - TerminationPolicies?: string; - NewInstancesProtectedFromScaleIn?: boolean; - Tags?: Tags; - } - - export interface CreateLaunchConfigurationParams { - LaunchConfigurationName: string; - AssociatePublicIpAddress?: boolean; - ImageId?: string; - KeyName?: string; - SecurityGroups?: string[]; - ClassicLinkVPCId?: string; - ClassicLinkVPCSecurityGroups?: string[]; - UserData?: string; - InstanceId?: string; - InstanceType?: string; - KernelId?: string; - RamdiskId?: string; - BlockDeviceMappings?: BlockDeviceMapping[]; - InstanceMonitoring?: InstanceMonitoring; - SpotPrice?: string; - IamInstanceProfile?: string; - EbsOptimized?: boolean; - PlacementTenancy?: string; - } - - export interface CreateOrUpdateTagsParams { - Tags: Tags[]; - } - - export interface DeleteAutoScalingGroupParams { - AutoScalingGroupName: string; - ForceDelete?: boolean; - } - - export interface DeleteLaunchConfigurationParams { - LaunchConfigurationName: string; - } - - export interface DeleteLifecycleHookParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - } - - export interface DeleteNotificationConfigurationParams { - AutoScalingGroupName: string; - TopicARN: string; - } - - export interface DeletePolicyParams { - PolicyName: string; - AutoScalingGroupName?: string; - } - - export interface DeleteScheduledActionParams { - AutoScalingGroupName: string; - ScheduledActionName: string; - } - - export interface DeleteTagsParams { - Tags: Tags[]; - } - - export interface DescribeAutoScalingGroupsParams { - AutoScalingGroupName?: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeAutoScalingInstancesParams { - InstanceIds?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLaunchConfigurationsParams { - LaunchConfigurationNames?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLifecycleHooksParams { - AutoScalingGroupName: string; - LifecycleHookNames?: string[]; - } - - export interface DescribeLoadBalancersParams { - AutoScalingGroupName: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeNotificationConfigurationsParams { - AutoScalingGroupName?: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribePoliciesParams { - AutoScalingGroupName?: string; - PolicyNames?: string[]; - PolicyTypes?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeScalingActivitiesParams { - AutoScalingGroupName?: string; - ActivityIds?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeScheduledActionsParams { - AutoScalingGroupName?: string; - ScheduledActionNames?: string[]; - StartTime?: Date; - EndTime?: Date; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeTagsParams { - Filters?: Filter[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DetachInstancesParams { - AutoScalingGroupName: string; - ShouldDecrementDesiredCapacity: boolean; - InstanceIds?: string[]; - } - - export interface DetachLoadBalancersParams { - AutoScalingGroupName: string; - LoadBalancerNames: string; - } - - export interface DetachLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - TargetGroupARNs: string[]; - } - - export interface DisableMetricsCollectionParams { - AutoScalingGroupName: string; - Metrics?: string[]; - } - - export interface EnableMetricsCollectionParams { - AutoScalingGroupName: string; - Granularity: string; - Metrics?: string[]; - } - - export interface EnterStandbyParams { - AutoScalingGroupName: string; - ShouldDecrementDesiredCapacity: boolean; - InstanceIds?: string[]; - } - - export interface ExecutePolicyParams { - PolicyName: string; - AutoScalingGroupName?: string; - HonorCooldown?: boolean; - MetricValue?: number; - BreachThreshold?: number; - } - - export interface ExitStandbyParams { - AutoScalingGroupName: string; - InstanceIds?: string[]; - } - - export interface PutLifecycleHookParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - LifecycleTransition?: string; - RoleARN?: string; - NotificationTargetARN?: string; - NotificationMetadata?: string; - HeartbeatTimeout?: number; - DefaultResult?: string; - } - - export interface PutNotificationConfigurationParams { - AutoScalingGroupName: string; - NotificationTypes: string[]; - TopicARN: string; - } - - export interface PutScalingPolicyParams { - AutoScalingGroupName: string; - AdjustmentType: string; - PolicyName: string; - PolicyType?: string; - MinAdjustmentStep?: number; - MinAdjustmentMagnitude?: number; - ScalingAdjustment?: number; - Cooldown?: number; - MetricAggregationType?: string; - StepAdjustments?: StepAdjustment[]; - EstimatedInstanceWarmup: number; - } - - export interface PutScheduledUpdateGroupActionParams { - AutoScalingGroupName: string; - ScheduledActionName: string; - Time?: Date; - StartTime?: Date; - EndTime?: Date; - Recurrence?: string; - MinSize?: number; - MaxSize?: number; - DesiredCapacity?: number; - } - - export interface RecordLifecycleActionHeartbeatParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - LifecycleActionToken?: string; - InstanceId?: string; - } - - export interface ResumeProcessesParams { - AutoScalingGroupName: string; - ScalingProcesses?: string[]; - } - - export interface SetDesiredCapacityParams { - AutoScalingGroupName: string; - DesiredCapacity: number; - HonorCooldown?: boolean; - } - - export interface SetInstanceHealthParams { - HealthStatus: string; - InstanceId: string; - ShouldRespectGracePeriod?: boolean; - } - - export interface SetInstanceProtectionParams { - AutoScalingGroupName: string; - InstanceIds: string[]; - ProtectedFromScaleIn: boolean; - } - - export interface SuspendProcessesParams { - AutoScalingGroupName: string; - ScalingProcesses?: string[]; - } - - export interface TerminateInstanceInAutoScalingGroupParams { - InstanceId: string; - ShouldDecrementDesiredCapacity: boolean; - } - - export interface UpdateAutoScalingGroupParams { - AutoScalingGroupName: string; - LaunchConfigurationName: string; - MinSize: number; - MaxSize: number; - DesiredCapacity: number; - DefaultCooldown: number; - AvailabilityZones: string[]; - HealthCheckType: string; - HealthCheckGracePeriod: number; - PlacementGroup: string; - VPCZoneIdentifier: string; - TerminationPolicies: string[]; - NewInstancesProtectedFromScaleIn?: boolean; - } + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; } + export interface AttachInstancesParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; + lifecycleActionToken?: string; + InstanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + Tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + AutoScalingGroupName: string; + ForceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + LaunchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + AutoScalingGroupName: string; + TopicARN: string; + } + + export interface DeletePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + } + + export interface DeleteTagsParams { + Tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribePoliciesParams { + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeTagsParams { + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DetachInstancesParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + AutoScalingGroupName: string; + Metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; + } + + export interface EnterStandbyParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface ExecutePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; + } + + export interface ExitStandbyParams { + AutoScalingGroupName: string; + InstanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; + } + + export interface PutScalingPolicyParams { + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; + } + } + export module SQS { From ca7ee532cee7e1ecac135c36cd719bbb6efefaa1 Mon Sep 17 00:00:00 2001 From: DzmitryDulko Date: Fri, 26 Aug 2016 14:37:43 -0700 Subject: [PATCH 013/154] Add page dimensions to jspdf/addPage --- jspdf/jspdf.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jspdf/jspdf.d.ts b/jspdf/jspdf.d.ts index 60246f04a1..e393e5fba1 100644 --- a/jspdf/jspdf.d.ts +++ b/jspdf/jspdf.d.ts @@ -42,7 +42,7 @@ declare module 'jspdf' { 'getPageInfo'(pageNumberOneBased:number):any; 'getCurrentPageInfo'():any; }; - addPage():jsPDF; + addPage(sizes?: number[]):jsPDF; setPage(n:number):jsPDF; insertPage(beforePage:number):jsPDF; movePage(targetPage:number, beforePage:number):jsPDF; From acdb7b6f5e633e8b361fdc4cac94d904d19c7e2e Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Wed, 31 Aug 2016 17:07:42 +0300 Subject: [PATCH 014/154] node-dir: added types for callback params --- node-dir/node-dir.d.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 857cdf7bdf..9f45441d4f 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -37,11 +37,11 @@ declare module "node-dir" { } export interface FileCallback { - (error: any, content: any, next: () => void): void; + (error: any, content: string, next: () => void): void; } export interface FileNamedCallback { - (error: any, content: any, filename: string, next: () => void): void; + (error: any, content: string, filename: string, next: () => void): void; } export interface StreamCallback { @@ -49,7 +49,11 @@ declare module "node-dir" { } export interface FinishedCallback { - (error: any, files: any): void; + (error: any, files: string[]): void; + } + export interface PathsResult { + files: string[]; + dirs: string[]; } export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; @@ -58,8 +62,9 @@ declare module "node-dir" { export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, finishedCallback?: FinishedCallback): void; - export function files(dir: string, callback: (error: any, files: any) => void): void; - export function subdirs(dir: string, callback: (error: any, subdirs: any) => void): void; - export function paths(dir: string, callback: (error: any, paths: any) => void): void; - export function paths(dir: string, combine: boolean, callback: (error: any, paths: any) => void): void; + export function files(dir: string, callback: (error: any, files: string[]) => void): void; + export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; + export function paths(dir: string, callback: (error: any, paths: PathsResult) => void): void; + export function paths(dir: string, combine: true, callback: (error: any, paths: string[]) => void): void; + export function paths(dir: string, combine: false, callback: (error: any, paths: PathsResult) => void): void; } From 9fbbb355351e32e7727ca35b885b62f3af50ec57 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:31:14 +0300 Subject: [PATCH 015/154] Buffer and ReadStream types --- node-dir/node-dir.d.ts | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 9f45441d4f..4ffaf0e093 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "node-dir" { + import { ReadStream } from "fs"; + export interface Options { // file encoding (defaults to 'utf8') encoding?: string; @@ -37,31 +39,28 @@ declare module "node-dir" { } export interface FileCallback { - (error: any, content: string, next: () => void): void; + (error: any, content: string | Buffer, next: () => void): void; } export interface FileNamedCallback { - (error: any, content: string, filename: string, next: () => void): void; + (error: any, content: string | Buffer, filename: string, next: () => void): void; } export interface StreamCallback { - (error: any, stream: any, next: () => void): void; + (error: any, stream: ReadStream, next: () => void): void; } export interface FinishedCallback { (error: any, files: string[]): void; } export interface PathsResult { - files: string[]; - dirs: string[]; + files: string[]; + dirs: string[]; } - export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, options: Options, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; - export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, - finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, finishedCallback?: FinishedCallback): void; export function files(dir: string, callback: (error: any, files: string[]) => void): void; export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; export function paths(dir: string, callback: (error: any, paths: PathsResult) => void): void; From dc316de06d44bdbc23ccf22d0b9869bdc36dc4fc Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:34:03 +0300 Subject: [PATCH 016/154] removed literal boolean types to pass Travis CI test --- node-dir/node-dir.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 4ffaf0e093..c1450cf172 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -64,6 +64,5 @@ declare module "node-dir" { export function files(dir: string, callback: (error: any, files: string[]) => void): void; export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; export function paths(dir: string, callback: (error: any, paths: PathsResult) => void): void; - export function paths(dir: string, combine: true, callback: (error: any, paths: string[]) => void): void; - export function paths(dir: string, combine: false, callback: (error: any, paths: PathsResult) => void): void; + export function paths(dir: string, combine: boolean, callback: (error: any, paths: string[] | PathsResult) => void): void; } From 9d32bda3023b89b75fb1c8289cbc96d9c89cd1a9 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:38:35 +0300 Subject: [PATCH 017/154] reference node in node-dir tests --- node-dir/node-dir-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node-dir/node-dir-tests.ts b/node-dir/node-dir-tests.ts index 6cc03ec538..c6442de20f 100644 --- a/node-dir/node-dir-tests.ts +++ b/node-dir/node-dir-tests.ts @@ -1,3 +1,4 @@ +/// /// import * as dir from "node-dir"; From eaebc356556dd02a3a530ae03b50b27b8bfd7017 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:51:40 +0300 Subject: [PATCH 018/154] reference node in node-dir --- node-dir/node-dir.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index c1450cf172..40843d3226 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/fshost/node-dir // Definitions by: Panu Horsmalahti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// declare module "node-dir" { import { ReadStream } from "fs"; From 69abf23874bad9cf8dbaa1650cdc6e4cba8c7582 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 15:03:32 +0300 Subject: [PATCH 019/154] revert accidental changes --- node-dir/node-dir.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 40843d3226..3b2c91dea2 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -59,8 +59,10 @@ declare module "node-dir" { dirs: string[]; } - export function readFiles(dir: string, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, options: Options, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, finishedCallback?: FinishedCallback): void; export function files(dir: string, callback: (error: any, files: string[]) => void): void; export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; From 2867a19221cd5e2449135aeed9f13f760b65f458 Mon Sep 17 00:00:00 2001 From: Alec Hill Date: Fri, 2 Sep 2016 13:57:19 +0100 Subject: [PATCH 020/154] Updated redux dock monitor and log monitor to include new optional props, and added typing to custom themes by adding base16 colour scheme typings --- base16/base16-tests.ts | 24 +++++++ base16/base16.d.ts | 70 +++++++++++++++++++ .../redux-devtools-dock-monitor-tests.tsx | 10 ++- .../redux-devtools-dock-monitor.d.ts | 31 +++++--- .../redux-devtools-log-monitor-tests.tsx | 32 ++++++++- .../redux-devtools-log-monitor.d.ts | 34 ++++++--- 6 files changed, 180 insertions(+), 21 deletions(-) create mode 100644 base16/base16-tests.ts create mode 100644 base16/base16.d.ts diff --git a/base16/base16-tests.ts b/base16/base16-tests.ts new file mode 100644 index 0000000000..e4cf78d559 --- /dev/null +++ b/base16/base16-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as base16 from 'base16'; + +const colorScheme: base16.ColorScheme = base16.solarized + +const scheme: string = colorScheme.scheme +const author: string = colorScheme.author +const base00: string = colorScheme.base00 +const base01: string = colorScheme.base01 +const base02: string = colorScheme.base02 +const base03: string = colorScheme.base03 +const base04: string = colorScheme.base04 +const base05: string = colorScheme.base05 +const base06: string = colorScheme.base06 +const base07: string = colorScheme.base07 +const base08: string = colorScheme.base08 +const base09: string = colorScheme.base09 +const base0A: string = colorScheme.base0A +const base0B: string = colorScheme.base0B +const base0C: string = colorScheme.base0C +const base0D: string = colorScheme.base0D +const base0E: string = colorScheme.base0E +const base0F: string = colorScheme.base0F diff --git a/base16/base16.d.ts b/base16/base16.d.ts new file mode 100644 index 0000000000..32717e99f2 --- /dev/null +++ b/base16/base16.d.ts @@ -0,0 +1,70 @@ +// Type definitions for base16-js 1.0.0 +// Project: https://github.com/gaearon/base16-js +// Definitions by: Alec Hill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'base16' { + + /** + * Type describing a syntax highlighting scheme as a JS object, as used in redux dev tools + * Based on https://github.com/chriskempson/base16 + */ + export interface ColorScheme { + scheme: string + author: string + base00: string + base01: string + base02: string + base03: string + base04: string + base05: string + base06: string + base07: string + base08: string + base09: string + base0A: string + base0B: string + base0C: string + base0D: string + base0E: string + base0F: string + } + + // predefined schemes... + export var threezerotwofour: ColorScheme + export var apathy: ColorScheme + export var ashes: ColorScheme + export var atelierDune: ColorScheme + export var atelierForest: ColorScheme + export var atelierHeath: ColorScheme + export var atelierLakeside: ColorScheme + export var atelierSeaside: ColorScheme + export var bespin: ColorScheme + export var brewer: ColorScheme + export var bright: ColorScheme + export var chalk: ColorScheme + export var codeschool: ColorScheme + export var colors: ColorScheme + export var eighties: ColorScheme + export var embers: ColorScheme + export var flat: ColorScheme + export var google: ColorScheme + export var grayscale: ColorScheme + export var greenscreen: ColorScheme + export var harmonic: ColorScheme + export var hopscotch: ColorScheme + export var isotope: ColorScheme + export var marrakesh: ColorScheme + export var monokai: ColorScheme + export var ocean: ColorScheme + export var paraiso: ColorScheme + export var pop: ColorScheme + export var railscasts: ColorScheme + export var shapeshifter: ColorScheme + export var solarized: ColorScheme + export var summerfruit: ColorScheme + export var tomorrow: ColorScheme + export var tube: ColorScheme + export var twilight: ColorScheme + +} diff --git a/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx b/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx index 00845bdc0a..deeb876fbc 100644 --- a/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx +++ b/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx @@ -4,4 +4,12 @@ import * as React from 'react' import DockMonitor from 'redux-devtools-dock-monitor' -let dockMonitor = \ No newline at end of file +let dockMonitor = + +let dockMonitorOptionalProps = diff --git a/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts b/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts index 09e3d96036..a3cb861c54 100644 --- a/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts +++ b/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-devtools-dock-monitor 1.0.1 +// Type definitions for redux-devtools-dock-monitor 1.1.1 // Project: https://github.com/gaearon/redux-devtools-dock-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,6 +8,8 @@ declare module "redux-devtools-dock-monitor" { import * as React from 'react' + type DockPosition = 'left' | 'top' | 'right' | 'bottom' + interface IDockMonitorProps { /** * Any valid Redux DevTools monitor. @@ -15,39 +17,48 @@ declare module "redux-devtools-dock-monitor" { children?: React.ReactNode /** - * A key or a key combination that toggles the dock visibility. + * A key or a key combination that toggles the dock visibility. * Must be recognizable by parse-key (for example, 'ctrl-h') */ toggleVisibilityKey: string /** - * A key or a key combination that toggles the dock position. + * A key or a key combination that toggles the dock position. * Must be recognizable by parse-key (for example, 'ctrl-w') */ changePositionKey: string + /** + * A key or a key combination that switches the currently visible monitor. + * Must be recognizable by parse-key (for example, 'ctrl-m') + * Required if you use more than one monitor. + * + * @default undefined + */ + changeMonitorKey?: string + /** * When true, the dock size is a fraction of the window size, fixed otherwise. - * + * * @default true */ fluid?: boolean /** - * Size of the dock. When fluid is true, a float (0.5 means half the window size). + * Size of the dock. When fluid is true, a float (0.5 means half the window size). * When fluid is false, a width in pixels - * + * * @default 0.3 (3/10th of the window size) */ defaultSize?: number /** - * Where the dock appears on the screen. + * Where the dock appears on the screen. * Valid values: 'left', 'top', 'right', 'bottom' - * + * * @default 'right' */ - defaultPosition?: string + defaultPosition?: DockPosition /** * @default true @@ -56,4 +67,4 @@ declare module "redux-devtools-dock-monitor" { } export default class DockMonitor extends React.Component {} -} \ No newline at end of file +} diff --git a/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx b/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx index dbcdbcf7a2..837bc17923 100644 --- a/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx +++ b/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx @@ -4,4 +4,34 @@ import * as React from 'react' import LogMonitor from 'redux-devtools-log-monitor' -let logMonitor = \ No newline at end of file +let logMonitor = + +let logMonitorWithStringTheme = + +const customTheme = { + scheme: 'Oscar Award Winner', + author: 'Nic Cage', + base00: '#000000', + base01: '#000000', + base02: '#000000', + base03: '#000000', + base04: '#000000', + base05: '#000000', + base06: '#000000', + base07: '#000000', + base08: '#000000', + base09: '#000000', + base0A: '#000000', + base0B: '#000000', + base0C: '#000000', + base0D: '#000000', + base0E: '#000000', + base0F: '#000000' +} + +let logMonitorWithCustomTheme = + +let logMonitorWithOtherOptProps = state} + preserveScrollTop={true} + expandActionRoot={true} + expandStateRoot={true} /> diff --git a/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts b/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts index 8c96c804da..bb558d5fdc 100644 --- a/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts +++ b/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts @@ -1,39 +1,55 @@ -// Type definitions for redux-devtools-log-monitor 1.0.1 +// Type definitions for redux-devtools-log-monitor 1.0.11 // Project: https://github.com/gaearon/redux-devtools-log-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// declare module "redux-devtools-log-monitor" { import * as React from 'react' + import {ColorScheme} from 'base16' interface ILogMonitorProps { /** - * Either a string referring to one of the themes provided by + * Either a string referring to one of the themes provided by * redux-devtools-themes or a custom object of the same format. - * + * * @see https://github.com/gaearon/redux-devtools-themes */ - theme?: string + theme?: string | ColorScheme /** * A function that selects the slice of the state for DevTools to show. - * + * * @example state => state.thePart.iCare.about. * @default state => state. */ select?: (state: any) => any /** - * When true, records the current scroll top every second so it - * can be restored on refresh. This only has effect when used together + * When true, records the current scroll top every second so it + * can be restored on refresh. This only has effect when used together * with persistState() enhancer from Redux DevTools. - * + * * @default true */ preserveScrollTop?: boolean + + /** + * When true, displays the action object expanded rather than collapsed. + * + * @default true + */ + expandActionRoot?: boolean + + /** + * When true, displays the state object expanded rather than collapsed. + * + * @default true + */ + expandStateRoot?: boolean } export default class LogMonitor extends React.Component {} -} \ No newline at end of file +} From 305bef7e2d9940e4cc40dd157afbabccbc3ef9d7 Mon Sep 17 00:00:00 2001 From: Bez Reyhan Date: Fri, 2 Sep 2016 12:38:19 -0700 Subject: [PATCH 021/154] allow tooltip prop of IconButton to be a ReactNode | string --- material-ui/material-ui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2913c0bd57..3f2894a9b6 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -536,7 +536,7 @@ declare namespace __MaterialUI { type horizontal = 'left' | 'middle' | 'right'; type vertical = 'top' | 'center' | 'bottom'; type direction = 'left' | 'right' | 'up' | 'down'; - + interface origin { horizontal: horizontal; vertical: vertical; @@ -745,7 +745,7 @@ declare namespace __MaterialUI { onMouseLeave?: React.MouseEventHandler; onMouseOut?: React.MouseEventHandler; style?: React.CSSProperties; - tooltip?: string; + tooltip?: React.ReactNode | string; tooltipPosition?: propTypes.cornersAndCenter; tooltipStyles?: React.CSSProperties; touch?: boolean; From 31b4db7233e018c9c74c7da2de96ec429501f8e2 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Fri, 9 Sep 2016 17:33:04 +0900 Subject: [PATCH 022/154] rewrite nock type definition --- nock/nock-tests.ts | 696 +++++++++++++++++++++++++++++++++++++++++---- nock/nock.d.ts | 237 ++++++++------- 2 files changed, 772 insertions(+), 161 deletions(-) diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index ffb456b420..20dbf6d04e 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -1,113 +1,118 @@ /// -import nock = require('nock'); +import * as nock from 'nock'; +import * as fs from 'fs'; -var inst: nock.Scope; +var scope: nock.Scope; +var inst: nock.Interceptor; var str: string; var strings: string[]; var bool: boolean; var data: string; var num: number; var obj: {}; -var objects: Object[]; +var defs: nock.NockDefinition[]; var value: any; var regex: RegExp; var options: nock.Options; -var headers: Object; +var headers: { [key: string]: string; }; -inst = inst.head(str); +inst = scope.head(str); -inst = inst.get(str); -inst = inst.get(str, data); +inst = scope.get(str); +inst = scope.get(str, data); -inst = inst.patch(str); -inst = inst.patch(str, str); -inst = inst.patch(str, obj); -inst = inst.patch(str, regex); +inst = scope.patch(str); +inst = scope.patch(str, str); +inst = scope.patch(str, obj); +inst = scope.patch(str, regex); -inst = inst.post(str); -inst = inst.post(str, data); -inst = inst.post(str, obj); -inst = inst.post(str, regex); +inst = scope.post(str); +inst = scope.post(str, data); +inst = scope.post(str, obj); +inst = scope.post(str, regex); -inst = inst.put(str); -inst = inst.put(str, data); -inst = inst.put(str, obj); -inst = inst.put(str, regex); +inst = scope.put(str); +inst = scope.put(str, data); +inst = scope.put(str, obj); +inst = scope.put(str, regex); -inst = inst.delete(str); -inst = inst.delete(str, data); -inst = inst.delete(str, obj); -inst = inst.delete(str, regex); +inst = scope.delete(str); +inst = scope.delete(str, data); +inst = scope.delete(str, obj); +inst = scope.delete(str, regex); -inst = inst.merge(str); -inst = inst.merge(str, data); -inst = inst.merge(str, obj); -inst = inst.merge(str, regex); +inst = scope.merge(str); +inst = scope.merge(str, data); +inst = scope.merge(str, obj); +inst = scope.merge(str, regex); inst = inst.query(obj); inst = inst.query(bool); -inst = inst.intercept(str, str); -inst = inst.intercept(str, str, str); -inst = inst.intercept(str, str, obj); -inst = inst.intercept(str, str, regex); -inst = inst.intercept(str, str, str, value); -inst = inst.intercept(str, str, obj, value); -inst = inst.intercept(str, str, regex, value); +inst = scope.intercept(str, str); +inst = scope.intercept(str, str, str); +inst = scope.intercept(str, str, obj); +inst = scope.intercept(str, str, regex); +inst = scope.intercept(str, str, str, value); +inst = scope.intercept(str, str, obj, value); +inst = scope.intercept(str, str, regex, value); -inst = inst.reply(num); -inst = inst.reply(num, str); +scope = inst.reply(num); +scope = inst.reply(num, str); -inst = inst.reply(num, str, headers); -inst = inst.reply(num, obj, headers); -inst = inst.reply(num, (uri: string, body: string) => { +scope = inst.reply(num, str, headers); +scope = inst.reply(num, obj, headers); +scope = inst.reply(num, (uri: string, body: string) => { return str; }); -inst = inst.reply(num, (uri: string, body: string) => { +scope = inst.reply(num, (uri: string, body: string) => { return str; }, headers); -inst = inst.replyWithFile(num, str); +scope = inst.replyWithFile(num, str); inst = inst.times(4); inst = inst.once(); inst = inst.twice(); inst = inst.thrice(); -inst = inst.defaultReplyHeaders(value); +scope = scope.defaultReplyHeaders(value); -inst = inst.matchHeader(str, str); -inst = inst.matchHeader(str, regex); -inst = inst.matchHeader(str, (val: string) => true); +scope = scope.matchHeader(str, str); +scope = scope.matchHeader(str, regex); +scope = scope.matchHeader(str, (val: string) => true); inst = inst.delay(num); inst = inst.delayConnection(num); -inst = inst.filteringPath(regex, str); -inst = inst.filteringPath((path: string) => { +scope = scope.filteringPath(regex, str); +scope = scope.filteringPath((path: string) => { return str; }); -inst = inst.filteringRequestBody(regex, str); -inst = inst.filteringRequestBody((path: string) => { +scope = scope.filteringRequestBody(regex, str); +scope = scope.filteringRequestBody((path: string) => { return str; }); -inst = inst.persist(); -inst = inst.log(() => { - -}); +scope = scope.log(() => { }); +scope = scope.persist(); +bool = scope.shouldPersist(); +scope = scope.replyContentLength(); +scope = scope.replyDate(); +scope = scope.replyDate(new Date()); inst = inst.delay(2000); +inst = inst.delay({ head: 1000, body: 1000 }); inst = inst.delayBody(2000); inst = inst.delayConnection(2000); inst.getTotalDelay(); inst = inst.socketDelay(2000); -inst.done(); -bool = inst.isDone(); -inst.restore(); +scope.done(); +bool = scope.isDone(); +scope.restore(); -objects = inst.pendingMocks(); +strings = scope.pendingMocks(); nock.recorder.rec(); nock.recorder.rec(true); @@ -115,6 +120,579 @@ nock.recorder.rec({ dont_print: true, output_objects: true }); +nock.recorder.clear(); +strings = nock.recorder.play() as string[]; +defs = nock.recorder.play() as nock.NockDefinition[]; + + +// Usage +var couchdb = nock('http://myapp.iriscouch.com') + .get('/users/1') + .reply(200, { + _id: '123ABC', + _rev: '946B7D1C', + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }); + +// Specifying hostname +var scope = nock('http://www.example.com') + .get('/resource') + .reply(200, 'domain matched'); +var scope = nock(/example\.com/) + .get('/resource') + .reply(200, 'domain regex matched'); + +// Specifying path +var scope = nock('http://www.example.com') + .get('/resource') + .reply(200, 'path matched'); + +var scope = nock('http://www.example.com') + .get(/source$/) + .reply(200, 'path using regex matched'); + +var scope = nock('http://www.example.com') + .get((uri) => { + return uri.indexOf('cats') >= 0; + }) + .reply(200, 'path using function matched'); + +// Specifying request body +var scope = nock('http://myapp.iriscouch.com') + .post('/users', { + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +var scope = nock('http://myapp.iriscouch.com') + .post('/users', /email=.?@gmail.com/gi) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +var scope = nock('http://myapp.iriscouch.com') + .post('/users', { + username: 'pgte', + password: /a.+/, + email: 'pedro.teixeira@gmail.com' + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +var scope = nock('http://myapp.iriscouch.com') + .post('/users', (body: any) => { + return body.id === '123ABC'; + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +// Specifying request query string +nock('http://example.com') + .get('/users') + .query({name: 'pedro', surname: 'teixeira'}) + .reply(200, {results: [{id: 'pgte'}]}); + +nock('http://example.com') + .get('/users') + .query({ + names: ['alice', 'bob'], + tags: { + alice: ['admin', 'tester'], + bob: ['tester'] + } + }) + .reply(200, {results: [{id: 'pgte'}]}); + +nock('http://example.com') + .get('/users') + .query((actualQueryObject: any) => { + // do some compare with the actual Query Object + // return true for matched + // return false for not matched + return true; + }) + .reply(200, {results: [{id: 'pgte'}]}); + +nock('http://example.com') + .get('/users') + .query(true) + .reply(200, {results: [{id: 'pgte'}]}); + +// Specifying replies +var scope = nock('http://myapp.iriscouch.com') + .get('/users/1') + .reply(404); + +var scope = nock('http://www.google.com') + .get('/') + .reply(200, 'Hello from Google!'); + +var scope = nock('http://myapp.iriscouch.com') + .get('/') + .reply(200, { + username: 'pgte', + email: 'pedro.teixeira@gmail.com', + _id: '4324243fsd' + }); + +var scope = nock('http://myapp.iriscouch.com') + .get('/') + .replyWithFile(200, __dirname + '/replies/user.json'); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply(201, (uri: string, requestBody: string) => { + return requestBody; + }); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply(201, (uri: string, requestBody: string, cb: nock.ReplyCallback) => { + fs.readFile('cat-poems.txt' , cb); // Error-first callback + }); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply((uri, requestBody) => { + return [ + 201, + 'THIS IS THE REPLY BODY', + {'header': 'value'} // optional headers + ]; + }); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply((uri, requestBody, cb) => { + setTimeout(() => { + cb(null, [201, 'THIS IS THE REPLY BODY']) + }, 1e3); + }); + +var scope = nock('http://www.google.com') + .get('/cat-poems') + .reply(200, (uri: string, requestBody: string) => { + return fs.createReadStream('cat-poems.txt'); + }); + +/// Access original request and headers +var scope = nock('http://www.google.com') + .get('/cat-poems') + .reply((uri, requestBody) => { + console.log('path:', this.req.path); + console.log('headers:', this.req.headers); + // ... + }); + +// Replying with errors +nock('http://www.google.com') + .get('/cat-poems') + .replyWithError('something awful happened'); + +nock('http://www.google.com') + .get('/cat-poems') + .replyWithError({'message': 'something awful happened', 'code': 'AWFUL_ERROR'}); + +// Specifying headers + +/// Specifying Request Headers +var scope = nock('http://www.example.com', { + reqheaders: { + 'authorization': 'Basic Auth' + } + }) + .get('/') + .reply(200); + +var scope = nock('http://www.example.com', { + reqheaders: { + 'X-My-Headers': (headerValue) => { + if (headerValue) { + return true; + } + return false; + }, + 'X-My-Awesome-Header': /Awesome/i + } + }) + .get('/') + .reply(200); + +var scope = nock('http://www.example.com', { + badheaders: ['cookie', 'x-forwarded-for'] + }) + .get('/') + .reply(200); + +var scope = nock('http://www.example.com') + .get('/') + .basicAuth({ + user: 'john', + pass: 'doe' + }) + .reply(200); + +/// Specifying Reply Headers +var scope = nock('http://www.headdy.com') + .get('/') + .reply(200, 'Hello World!', { + 'X-My-Headers': 'My Header value' + }); + +var scope = nock('http://www.headdy.com') + .get('/') + .reply(200, 'Hello World!', { + 'X-My-Headers': (req, res, body) => { + return body.toString(); + } + }); + +// Default Reply Headers +var scope = nock('http://www.headdy.com') + .defaultReplyHeaders({ + 'X-Powered-By': 'Rails', + 'Content-Type': 'application/json' + }) + .get('/') + .reply(200, 'The default headers should come too'); + +var scope = nock('http://www.headdy.com') + .defaultReplyHeaders({ + 'Content-Length': (req, res, body) => { + return body.length; + } + }) + .get('/') + .reply(200, 'The default headers should come too'); + +// Including Content-Length Header Automatically +var scope = nock('http://www.headdy.com') + .replyContentLength() + .get('/') + .reply(200, { hello: 'world' }); + +// Including Date Header Automatically +var scope = nock('http://www.headdy.com') + .replyDate(new Date(2015, 0, 1)) // defaults to now, must use a Date object + .get('/') + .reply(200, { hello: 'world' }); + +// HTTP Verbs +nock('http://my.domain.com') + .intercept('/path', 'PATCH') + .reply(304); + +// Support for HTTP and HTTPS +var scope = nock('https://secure.my.server.com'); + +// Non-standard ports +var scope = nock('http://my.server.com:8081'); + +// Repeat response n times +nock('http://zombo.com').get('/').times(4).reply(200, 'Ok'); +nock('http://zombo.com').get('/').once().reply(200, 'Ok'); +nock('http://zombo.com').get('/').twice().reply(200, 'Ok'); +nock('http://zombo.com').get('/').thrice().reply(200, 'Ok'); + +// Delay the response body +nock('http://my.server.com') + .get('/') + .delayBody(2000) // 2 seconds + .reply(200, '') + +// Delay the response +nock('http://my.server.com') + .get('/') + .delay(2000) // 2 seconds delay will be applied to the response header. + .reply(200, '') + +nock('http://my.server.com') + .get('/') + .delay({ + head: 2000, // header will be delayed for 2 seconds, i.e. the whole response will be delayed for 2 seconds. + body: 3000 // body will be delayed for another 3 seconds after header is sent out. + }) + .reply(200, '') + +// Delay the connection +nock('http://my.server.com') + .get('/') + .socketDelay(2000) // 2 seconds + .delayConnection(1000) + .reply(200, '') + +// Chaining +var scope = nock('http://myapp.iriscouch.com') + .get('/users/1') + .reply(404) + .post('/users', { + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }) + .get('/users/123ABC') + .reply(200, { + _id: '123ABC', + _rev: '946B7D1C', + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }); + +// Scope filtering +var scope = nock('https://api.dropbox.com', { +filteringScope: (scope: string) => { + return /^https:\/\/api[0-9]*.dropbox.com/.test(scope); + } + }) + .get('/1/metadata/auto/Photos?include_deleted=false&list=true') + .reply(200); + +// Path filtering +var scope = nock('http://api.myservice.com') + .filteringPath(/password=[^&]*/g, 'password=XXX') + .get('/users/1?password=XXX') + .reply(200, 'user'); + +var scope = nock('http://api.myservice.com') + .filteringPath((path) => { + return '/ABC'; + }) + .get('/ABC') + .reply(200, 'user'); + +// Request Body filtering +var scope = nock('http://api.myservice.com') + .filteringRequestBody(/password=[^&]*/g, 'password=XXX') + .post('/users/1', 'data=ABC&password=XXX') + .reply(201, 'OK'); + +var scope = nock('http://api.myservice.com') + .filteringRequestBody((body) => { + return 'ABC'; + }) + .post('/', 'ABC') + .reply(201, 'OK'); + +// Request Headers Matching +var scope = nock('http://api.myservice.com') + .matchHeader('accept', 'application/json') + .get('/') + .reply(200, { + data: 'hello world' + }) + +var scope = nock('http://api.myservice.com') + .matchHeader('User-Agent', /Mozilla\/.*/) + .get('/') + .reply(200, { + data: 'hello world' + }) + +var scope = nock('http://api.myservice.com') + .matchHeader('content-length', (val) => { + return Number(val) >= 1000; + }) + .get('/') + .reply(200, { + data: 'hello world' + }) + +// Allow unmocked requests on a mocked hostname +options = {allowUnmocked: true}; +var scope = nock('http://my.existing.service.com', options) + .get('/my/url') + .reply(200, 'OK!'); + +// Expectations +var google = nock('http://google.com') + .get('/') + .reply(200, 'Hello from Google!'); +setTimeout(() => { + google.done(); // will throw an assertion error if meanwhile a "GET http://google.com" was not performed. +}, 5000); + +/// .isDone() +var scope = nock('http://google.com') + .get('/') + .reply(200); +scope.isDone(); // will return false + +nock.isDone(); + +/// .cleanAll() +nock.cleanAll(); + +/// .persist() +var scope = nock('http://persisssists.con') + .persist() + .get('/') + .reply(200, 'Persisting all the way'); + +/// .pendingMocks() +if (!scope.isDone()) { + console.error('pending mocks: %j', scope.pendingMocks()); +} +console.error('pending mocks: %j', nock.pendingMocks()); + +// Logging +var google = nock('http://google.com') + .log(console.log); + +// Restoring +nock.restore(); + +// Enable/Disable real HTTP request +nock.disableNetConnect(); +nock.enableNetConnect(); + +// using a string +nock.enableNetConnect('amazon.com'); + +// or a RegExp +nock.enableNetConnect(/(amazon|github).com/); + +nock.disableNetConnect(); +nock.enableNetConnect('127.0.0.1'); //Allow localhost connections so we can test local routes and mock servers. + +nock.cleanAll(); +nock.enableNetConnect(); + + +// Recording +nock.recorder.rec(); + +/// dont_print option +nock.recorder.rec({ + dont_print: true +}); +// ... some HTTP calls +var nockCalls = nock.recorder.play(); + +/// output_objects option +nock.recorder.rec({ + output_objects: true +}); +// ... some HTTP calls +var nockCallObjects = nock.recorder.play(); + +var pathToJson: string; +var nocks = nock.load(pathToJson); +nocks.forEach((nock) => { + nock = nock.filteringRequestBody((body: string) => { + return body; + }); +}); + +// Pre-process the nock definitions as scope filtering has to be defined before the nocks are defined (due to its very hacky nature). +var nockDefs = nock.loadDefs(pathToJson); +nockDefs.forEach((def) => { + // Do something with the definition object e.g. scope filtering. + def.options = def.options || {}; + def.options.filteringScope = (scope: string) => { + return /^https:\/\/api[0-9]*.dropbox.com/.test(scope); + }; +}); +// Load the nocks from pre-processed definitions. +var nocks = nock.define(nockDefs); + +/// enable_reqheaders_recording option +nock.recorder.rec({ + dont_print: true, + output_objects: true, + enable_reqheaders_recording: true +}); + +/// logging option +var nullAppender = (content: string) => { }; +nock.recorder.rec({ + logging: nullAppender +}); + +/// use_separator option +nock.recorder.rec({ + use_separator: false +}); + + +// .removeInterceptor() +nock.removeInterceptor({ + hostname : 'localhost', + path : '/mockedResource' +}); +nock.removeInterceptor({ + hostname : 'localhost', + path : '/login', + method: 'POST', + proto : 'https' +}); + +var interceptor = nock('http://example.org') + .get('somePath'); +nock.removeInterceptor(interceptor); + + +// Events +/// Global no match event +nock.emitter.on('no match', (req: any) => { }); + + +// Nock Back +/// Setup +import { back as nockBack } from 'nock'; + +nockBack.fixtures = '/path/to/fixtures/'; +nockBack.setMode('record'); + +/// Usage +nockBack.setMode('record'); +nockBack.fixtures = './nockFixtures'; //this only needs to be set once in your test helper + +var before = (def: nock.NockDefinition) => { + def.options = def.options || {}; + def.options.filteringScope = (scope: string) => { + return /^https:\/\/api[0-9]*.dropbox.com/.test(scope); + }; +}; +var after = (scope: nock.Scope) => { + scope = scope.filteringRequestBody((body: string): string => { + return body; + }); +}; + +// recording of the fixture +declare var request: any; +nockBack('zomboFixture.json', { before, after }, (nockDone: () => void) => { + request.get('http://zombo.com', (err: any, res: any, body: string) => { + nockDone(); + // usage of the created fixture + nockBack('zomboFixture.json', (nockDone: () => void) => { + nockDone(); //never gets here + }); + }); +}); + + + -strings = nock.recorder.play(); -objects = nock.recorder.play(); diff --git a/nock/nock.d.ts b/nock/nock.d.ts index 615ec0d3ca..d98d390b10 100644 --- a/nock/nock.d.ts +++ b/nock/nock.d.ts @@ -1,131 +1,164 @@ -// Type definitions for nock v0.54.0 -// Project: https://github.com/pgte/nock -// Definitions by: bonnici +// Type definitions for nock v8.0.0 +// Project: https://github.com/node-nock/nock +// Definitions by: bonnici , Horiuchi_H // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Imported from: https://github.com/soywiz/typescript-node-definitions/nock.d.ts +/// declare module "nock" { - export = nock; + export = nock; - function nock (host: string, options?: nock.Options): nock.Scope; + function nock(basePath: string | RegExp, options?: nock.Options): nock.Scope; - namespace nock { - export function cleanAll(): void; + namespace nock { + export function cleanAll(): void; - export function disableNetConnect(): void; - export function enableNetConnect(): void; - export function enableNetConnect(regex: RegExp): void; - export function enableNetConnect(domain: string): void; - - export function load(path: string): Object[]; - export function restore(): void; + export function activate(): void; + export function isActive(): boolean; + export function isDone(): boolean; + export function pendingMocks(): void; + export function removeInterceptor(interceptor: Interceptor | RequestOptions): boolean; + export function disableNetConnect(): void; + export function enableNetConnect(matcher?: string | RegExp): void; - export var recorder: Recorder; + export function load(path: string): Scope[]; + export function loadDefs(path: string): NockDefinition[]; + export function define(defs: NockDefinition[]): Scope[]; - export interface Scope { - get(path: string, data?: string): Scope; - get(path: RegExp, data?: string): Scope; + export var emitter: NodeJS.EventEmitter; - post(path: string, data?: string): Scope; - post(path: string, data?: Object): Scope; - post(path: string, regex?: RegExp): Scope; - post(path: RegExp, data?: string): Scope; - post(path: RegExp, data?: Object): Scope; - post(path: RegExp, regex?: RegExp): Scope; + export var recorder: Recorder; + export function restore(): void; - patch(path: string, data?: string): Scope; - patch(path: string, data?: Object): Scope; - patch(path: string, regex?: RegExp): Scope; - patch(path: RegExp, data?: string): Scope; - patch(path: RegExp, data?: Object): Scope; - patch(path: RegExp, regex?: RegExp): Scope; + export var back: NockBack; - put(path: string, data?: string): Scope; - put(path: string, data?: Object): Scope; - put(path: string, regex?: RegExp): Scope; - put(path: RegExp, data?: string): Scope; - put(path: RegExp, data?: Object): Scope; - put(path: RegExp, regex?: RegExp): Scope; + type HttpHeaders = { [key: string]: string | { (req: any, res: any, body: string): any; }; }; + type InterceptFunction = ( + uri: string | RegExp | { (uri: string): boolean; }, + requestBody?: string | RegExp | { (body: any): boolean; } | any + ) => Interceptor; + export type ReplyCallback = (err: any, result: ReplyCallbackResult) => void; + type ReplyCallbackResult = string | [number, string | any] | [number, string | any, HttpHeaders] | any; - head(path: string): Scope; - head(path: RegExp): Scope; - delete(path: string, data?: string): Scope; - delete(path: string, data?: Object): Scope; - delete(path: string, regex?: RegExp): Scope; - delete(path: RegExp, data?: string): Scope; - delete(path: RegExp, data?: Object): Scope; - delete(path: RegExp, regex?: RegExp): Scope; + export interface Scope extends NodeJS.EventEmitter { + get: InterceptFunction; + post: InterceptFunction; + put: InterceptFunction; + head: InterceptFunction; + patch: InterceptFunction; + merge: InterceptFunction; + delete: InterceptFunction; - merge(path: string, data?: string): Scope; - merge(path: string, data?: Object): Scope; - merge(path: string, regex?: RegExp): Scope; - merge(path: RegExp, data?: string): Scope; - merge(path: RegExp, data?: Object): Scope; - merge(path: RegExp, regex?: RegExp): Scope; + intercept: ( + uri: string | RegExp | { (uri: string): boolean; }, + method: string, + requestBody?: string | RegExp | { (body: any): boolean; } | any, + options?: Options + ) => Interceptor; - query(params: any): Scope; - query(acceptAnyParams: boolean): Scope; - intercept(path: string, verb: string, body?: string, options?: any): Scope; - intercept(path: string, verb: string, body?: Object, options?: any): Scope; - intercept(path: string, verb: string, body?: RegExp, options?: any): Scope; - intercept(path: RegExp, verb: string, body?: string, options?: any): Scope; - intercept(path: RegExp, verb: string, body?: Object, options?: any): Scope; - intercept(path: RegExp, verb: string, body?: RegExp, options?: any): Scope; + defaultReplyHeaders(headers: HttpHeaders): this; + matchHeader(name: string, value: string | RegExp | { (value: string): boolean; }): this; + filteringPath(regex: RegExp, replace: string): this; + filteringPath(fn: (path: string) => string): this; + filteringRequestBody(regex: RegExp, replace: string): this; + filteringRequestBody(fn: (body: string) => string): this; - reply(responseCode: number, body?: string, headers?: Object): Scope; - reply(responseCode: number, body?: Object, headers?: Object): Scope; - reply(responseCode: number, callback: (uri: string, body: string) => string, headers?: Object): Scope; - replyWithFile(responseCode: number, fileName: string): Scope; - replyWithError(errorMessage: string): Scope; + log(out: () => void): this; + persist(): this; + shouldPersist(): boolean; + replyContentLength(): this; + replyDate(d?: Date): this; - defaultReplyHeaders(headers: Object): Scope; + done(): void; + isDone(): boolean; + restore(): void; + pendingMocks(): string[]; + } - matchHeader(name: string, value: string): Scope; - matchHeader(name: string, regex: RegExp): Scope; - matchHeader(name: string, fn: (value: string) => boolean): Scope; + export interface Interceptor { + query(params: boolean | { (querObject: any): boolean; } | any): this; - filteringPath(regex: RegExp, replace: string): Scope; - filteringPath(fn: (path: string) => string): Scope; - filteringRequestBody(regex: RegExp, replace: string): Scope; - filteringRequestBody(fn: (path: string) => string): Scope; + reply(responseCode: number, body?: string | any, headers?: HttpHeaders): Scope; + reply(responseCode: number, callback: (uri: string, body: string, cb?: ReplyCallback) => ReplyCallbackResult, headers?: HttpHeaders): Scope; + reply(callback: (uri: string, body: string, cb?: ReplyCallback) => ReplyCallbackResult, headers?: HttpHeaders): Scope; + replyWithError(errorMessage: string | any): Scope; + replyWithFile(responseCode: number, fileName: string, headers?: HttpHeaders): Scope; - persist(): Scope; - log(out: () => void): Scope; + basicAuth(options: { user: string; pass?: string; }): this; - delay(timeMs: number): Scope; - delayBody(timeMs: number): Scope; - delayConnection(timeMs: number): Scope; - getTotalDelay(): number; - socketDelay(timeMs: number): Scope; + times(newCounter: number): this; + once(): this; + twice(): this; + thrice(): this; - times(repeats: number): Scope; - once(): Scope; - twice(): Scope; - thrice(): Scope; + delay(opts: number | { head?: number; body?: number; }): this; + delayBody(timeMs: number): this; + delayConnection(timeMs: number): this; + getTotalDelay(): number; + socketDelay(timeMs: number): this; + } - done(): void; - isDone(): boolean; - restore(): void; - pendingMocks(): Object[]; - } + export interface Options { + allowUnmocked?: boolean; + reqheaders?: { [key: string]: string | RegExp | { (headerValue: string): boolean; }; }; + badheaders?: string[]; + filteringScope?: { (scope: string): boolean; }; + } - export interface Recorder { - rec(capture?: boolean): void; - rec(options?: RecorderOptions): void; - play(): any[]; - } + export interface RequestOptions { + proto?: string; + _https_?: boolean; + hostname?: string; + host?: string; + port?: number; + method?: string; + path?: string; + } - export interface Options { - allowUnmocked?: boolean; - } + export interface Recorder { + rec(options?: boolean | RecorderOptions): void; + clear(): void; + play(): string[] | NockDefinition[]; + } - export interface RecorderOptions { - dont_print?: boolean; - output_objects?: boolean; - enable_reqheaders_recording?: boolean; - } - } + export interface RecorderOptions { + dont_print?: boolean; + output_objects?: boolean; + enable_reqheaders_recording?: boolean; + logging?: (content: string) => void; + use_separator?: boolean; + } + + export interface NockDefinition { + scope: string; + port?: number | string; + method?: string; + path: string; + body?: string | any; + status?: number; + response?: string | any; + headers?: HttpHeaders; + reqheaders?: { [key: string]: string | RegExp | { (headerValue: string): boolean; }; }; + options?: Options; + } + + export type NockBackMode = "wild" | "dryrun" | "record" | "lockdown"; + + export interface NockBack { + fixtures: string; + setMode(mode: NockBackMode): void; + + (fixtureName: string, nockedFn: (nockDone: () => void) => void): void; + (fixtureName: string, options: NockBackOptions, nockedFn: (nockDone: () => void) => void): void; + } + + export interface NockBackOptions { + before?: (def: NockDefinition) => void; + after?: (scope: Scope) => void; + afterRecord?: (defs: NockDefinition[]) => NockDefinition[]; + recorder?: RecorderOptions; + } + } } From 33377a68598194d155764feb4a4ef33f606b220a Mon Sep 17 00:00:00 2001 From: Tomas Date: Tue, 13 Sep 2016 11:37:10 +0100 Subject: [PATCH 023/154] Fixing removeAllListeners definition - argument optional --- wolfy87-eventemitter/wolfy87-eventemitter.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts index 8291c50c11..d9af289d1a 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts @@ -405,14 +405,14 @@ declare namespace Wolfy87EventEmitter { * * Added to mirror the node API. */ - removeAllListeners(event: string): EventEmitter; + removeAllListeners(event?: string): EventEmitter; /** * Alias of removeEvent. * * Added to mirror the node API. */ - removeAllListeners(event: RegExp): EventEmitter; + removeAllListeners(event?: RegExp): EventEmitter; /** * Emits an event of your choice. From d34c7a7cdd8b58b40eabc3fcc0ac90d799fca4ba Mon Sep 17 00:00:00 2001 From: Marc Date: Tue, 13 Sep 2016 10:35:48 -0400 Subject: [PATCH 024/154] requirejs.RequireConfig Add a missing signature for urlArgs property of the RequireConfig object. --- requirejs/require.d.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 3905945187..1c5b4088c1 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -185,8 +185,28 @@ interface RequireConfig { * * @example * urlArgs: "bust= + (new Date()).getTime() + * + * As of RequireJS 2.2.0, urlArgs can be a function. If a + * function, it will receive the module ID and the URL as + * parameters, and it should return a string that will be added + * to the end of the URL. Return an empty string if no args. + * Be sure to take care of adding the '?' or '&' depending on + * the existing state of the URL. + * + * @example + + * requirejs.config({ + * urlArgs: function(id, url) { + * var args = 'v=1'; + * if (url.indexOf('view.html') !== -1) { + * args = 'v=2' + * } + * + * return (url.indexOf('?') === -1 ? '?' : '&') + args; + * } + * }); **/ - urlArgs?: string; + urlArgs?: string | { (id: string, url: string): string; }; /** * Specify the value for the type="" attribute used for script From feae95f169c4892f7e525cbe9d7f677785c99210 Mon Sep 17 00:00:00 2001 From: Gary Roberts Date: Wed, 14 Sep 2016 09:03:34 +0100 Subject: [PATCH 025/154] Update react-router.d.ts Changed react-router RouteComponentProps comment to properly reflect routeParams resolving to type string (not number). As per documentation here: https://github.com/ReactTraining/react-router/blob/master/docs/API.md#routeparams --- react-router/react-router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..767cca1e2f 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -39,10 +39,10 @@ declare namespace ReactRouter { type RouteComponent = Component // use the following interface in an app code to get access to route param values, history, location... - // interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: number }> {} + // interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: string }> {} // somewhere in MyComponent // ... - // let id = this.props.routeParams.id + // let id = parseInt(this.props.routeParams.id, 10); // ... // this.props.history. ... // ... From ab5876b6df73ae917772efcc161efe635d019b51 Mon Sep 17 00:00:00 2001 From: rvassar Date: Wed, 14 Sep 2016 09:17:23 -0700 Subject: [PATCH 026/154] Updated the Attribution class with constructor and methods. --- openlayers/openlayers.d.ts | 62 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 7cc216f1c2..346a9edef6 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -88,6 +88,34 @@ declare namespace olx { target?: Element; } + interface AttributionControlOptions { + /*** CSS class name. Default is ol-attribution.*/ + className?: string; + /*** Target.*/ + target?: Element; + /** + * Specify if attributions can be collapsed. If you use an OSM source, + * should be set to false — see OSM Copyright — Default is true. + */ + collapsible?: boolean; + /*** Specify if attributions should be collapsed at startup. Default is true.*/ + collapsed?: boolean; + /*** Text label to use for the button tip. Default is "Attributions".*/ + tipLabel?: Array | ol.Collection; + /** + * Text label to use for the collapsed attributions button. Default is i. + * Instead of text, also a Node (e.g. a span element) can be used. + */ + label?: string | Node; + /** + * Text label to use for the expanded attributions button. Default is ». + * Instead of text, also a Node (e.g. a span element) can be used. + */ + collapseLabel?: string | Node; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + } + interface AttributionOptions { /** HTML markup for this attribution. */ @@ -2841,7 +2869,41 @@ declare namespace ol { } + /** + * Control to show all the attributions associated with the layer sources in the map. + * This control is one of the default controls included in maps. By default it will show in the bottom right portion of the map, + * but this can be changed by using a css selector for .ol-attribution. + */ class Attribution extends Control { + constructor(opt_options?: olx.AttributionControlOptions); + /** + * Update the attribution element. + * @param mapEvent + */ + render(mapEvent: ol.MapEvent): void; + + /** + * Return true when the attribution is currently collapsed or false otherwise. + */ + getCollapsed(): boolean; + + /** + * Return true if the attribution is collapsible, false otherwise. + */ + getCollapsible(): boolean; + + /** + * Collapse or expand the attribution according to the passed parameter. Will not do anything if the attribution isn't + * collapsible or if the current collapsed state is already the one requested. + * @param collapsed + */ + setCollapsed(collapsed: boolean): void; + + /** + * Set whether the attribution should be collapsible. + * @param collapsible + */ + setCollapsible(collapsible: boolean): void; } class FullScreen extends Control { From 47588ba8f9a2ceb05acef2ec2c69263cf057405d Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Wed, 14 Sep 2016 11:27:33 -0700 Subject: [PATCH 027/154] [knockout] Introduce specialized signatures for subscribe method, specifically common "change" and "beforeChange" Add subscribe for "arrayChange" event for observable array (fixes #11203) Improve KnockoutArrayChange status typing. --- knockout/knockout.d.ts | 11 ++++++++-- knockout/knockoutamd-tests.ts | 2 +- knockout/tests/knockout-tests.ts | 35 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6321cff0a5..f0e9fe023f 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -61,8 +61,10 @@ interface KnockoutSubscription { } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { - subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; getSubscriptionsCount(): number; } @@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic { } interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { + subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } @@ -325,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: string; + status: "added" | "deleted"; value: T; index: number; moved?: number; diff --git a/knockout/knockoutamd-tests.ts b/knockout/knockoutamd-tests.ts index c874c6208b..9ee6658335 100644 --- a/knockout/knockoutamd-tests.ts +++ b/knockout/knockoutamd-tests.ts @@ -1,6 +1,6 @@ /// -import ko = require("knockout"); +import ko = require("knockout"); var myArray = ko.observableArray([1, 2, 3]); diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 8da6c12950..122617b180 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -680,3 +680,38 @@ function test_tasks() { setTimeout(callback, 0); }; } + +function observableEventsTests() { + var observable = ko.observable(1); + observable.subscribe(value => { + var num: number = value; + }); + observable.subscribe(value => { + var num: number = value; + }, null, "change"); + observable.subscribe(value => { + var num: number = value; + }, null, "beforeChange"); +} + +function observableArrayEventsTests() { + var observableArray = ko.observableArray([1, 2, 3, 4]); + observableArray.subscribe(array => { + var arr: number[] = array; + }); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "change"); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "beforeChange"); + var count = 0; + observableArray.subscribe(changes => { + changes.forEach(change => { + if (change.status == "added") + count++; + else if (change.status == "deleted") + count--; + }); + }, null, "arrayChange"); +} \ No newline at end of file From 27347de728273acb8e0dcc917753164c96acb6a0 Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Wed, 14 Sep 2016 14:13:28 -0500 Subject: [PATCH 028/154] add route-bound methods for scoped service Documentation: https://github.com/mgonto/restangular#decoupled-restangular-service When configured via `Restangular.service('route')`, the route is bound to some functions. This change overrides those functions with the correct signatures. --- restangular/restangular.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 8daa5c0b08..dd059cea2e 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -90,11 +90,20 @@ declare namespace restangular { withConfig(configurer: (RestangularProvider: IProvider) => any): IService; restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; restangularizeCollection(parent: any, element: any, route: string): ICollection; - service(route: string, parent?: any): IService; + service(route: string, parent?: any): IScopedService; stripRestangular(element: any): any; extendModel(route: string, extender: (model: IElement) => any): void; extendCollection(route: string, extender: (collection: ICollection) => any): void; } + + interface IScopedService extends IService { + one(id: number): IElement; + one(id: string): IElement; + post(elementToPost: any, queryParams?: any, headers?: any): IPromise; + post(elementToPost: T, queryParams?: any, headers?: any): IPromise; + getList(queryParams?: any, headers?: any): ICollectionPromise; + getList(queryParams?: any, headers?: any): ICollectionPromise; + } interface IElement extends IService { get(queryParams?: any, headers?: any): IPromise; From 36d40a63a05b5cb3413737fbdf7c9a2a26f211fd Mon Sep 17 00:00:00 2001 From: Craig Date: Wed, 14 Sep 2016 16:56:35 -0700 Subject: [PATCH 029/154] types(selenium-webdriver): revert 2.44 as default (#11226) - previous change would break installing angular-protractor ambient types - adding myself as author --- angular-protractor/angular-protractor.d.ts | 2 +- protractor-helpers/protractor-helpers.d.ts | 2 +- .../protractor-http-mock.d.ts | 2 +- .../selenium-webdriver-2.53.1-tests.ts | 1144 +++++ ....0.d.ts => selenium-webdriver-2.53.1.d.ts} | 3994 ++++++++++------ .../selenium-webdriver-tests.ts | 249 +- selenium-webdriver/selenium-webdriver.d.ts | 4250 ++++++----------- 7 files changed, 5444 insertions(+), 4199 deletions(-) create mode 100644 selenium-webdriver/selenium-webdriver-2.53.1-tests.ts rename selenium-webdriver/{selenium-webdriver-2.44.0.d.ts => selenium-webdriver-2.53.1.d.ts} (60%) diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index add8264b7e..d33eeddace 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bill Armstrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace protractor { //region Wrapped webdriver Items diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 16d67cfbb9..3966acd36e 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// // ElementArrayFinder diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index 2300246e43..29d6dfb276 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace mock { interface ProtractorHttpMock { diff --git a/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts b/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts new file mode 100644 index 0000000000..77c68bb58d --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts @@ -0,0 +1,1144 @@ +/// + +function TestChromeDriver() { + var driver: chrome.Driver = new chrome.Driver(); + driver = new chrome.Driver(webdriver.Capabilities.chrome()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestChromeOptions() { + var options: chrome.Options = new chrome.Options(); + options = chrome.Options.fromCapabilities(webdriver.Capabilities.chrome()); + + options = options.addArguments("a", "b", "c"); + options = options.addExtensions("a", "b", "c"); + options = options.excludeSwitches("a", "b", "c"); + options = options.detachDriver(true); + options = options.setChromeBinaryPath("path"); + options = options.setChromeLogFile("logfile"); + options = options.setLocalState("state"); + options = options.androidActivity("com.example.Activity"); + options = options.androidDeviceSerial("emulator-5554"); + options = options.androidChrome(); + options = options.androidPackage("com.android.chrome"); + options = options.androidProcess("com.android.chrome"); + options = options.androidUseRunningApp(true); + options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setPerfLoggingPrefs({enableNetwork: true, enablePage: true, enableTimeline: true, tracingCategories: "category", bufferUsageReportingInterval: 1000}); + options = options.setProxy({ proxyType: "proxyType" }); + options = options.setUserPreferences("preferences"); + var capabilities: webdriver.Capabilities = options.toCapabilities(); + capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); +} + +function TestServiceBuilder() { + var builder: chrome.ServiceBuilder = new chrome.ServiceBuilder(); + builder = new chrome.ServiceBuilder("exe"); + + var anything: any = builder.build(); + builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); + builder = builder.loggingTo("path"); + builder = builder.enableVerboseLogging(); + builder = builder.setNumHttpThreads(5); + builder = builder.setUrlBasePath("path"); + builder = builder.setStdio("config"); + builder = builder.setStdio(["A", "B"]); + builder = builder.withEnvironment({ "A": "a", "B": "b" }); +} + +function TestChromeModule() { + var service: any = chrome.getDefaultService(); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); +} + +function TestBinary() { + var binary: firefox.Binary = new firefox.Binary(); + binary = new firefox.Binary("exe"); + + binary.addArguments("A", "B", "C"); + var promise: webdriver.promise.Promise = binary.kill(); + binary.launch("profile").then(function (result: any) { }); +} + +function TestFirefoxDriver() { + var driver: firefox.Driver = new firefox.Driver(); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestFirefoxOptions() { + var options: firefox.Options = new firefox.Options(); + + options = options.setBinary("binary"); + options = options.setBinary(new firefox.Binary()); + options = options.setLoggingPreferences(new webdriver.logging.Preferences()); + options = options.setProfile("profile"); + options = options.setProfile(new firefox.Profile()); + options = options.setProxy({ proxyType: "proxy" }); + var capabilities: webdriver.Capabilities = options.toCapabilities(); +} + +function TestFirefoxProfile() { + var profile: firefox.Profile = new firefox.Profile(); + profile = new firefox.Profile("dir"); + + var bool: boolean = profile.acceptUntrustedCerts(); + profile.addExtension("ext"); + bool = profile.assumeUntrustedCertIssuer(); + profile.encode().then(function (prof: string) { }); + var num: number = profile.getPort(); + var anything: any = profile.getPreference("key"); + bool = profile.nativeEventsEnabled(); + profile.setAcceptUntrustedCerts(true); + profile.setAssumeUntrustedCertIssuer(true); + profile.setNativeEventsEnabled(true); + profile.setPort(8080); + profile.setPreference("key", "value"); + profile.setPreference("key", 5); + profile.setPreference("key", true); + var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); + stringPromise = profile.writeToDisk(true); +} + +function TestExecutors() { + var exec: webdriver.Executor = executors.createExecutor("url"); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); +} + +function TestBuilder() { + var builder: webdriver.Builder = new webdriver.Builder(); + + var driver: webdriver.WebDriver = builder.build(); + builder = builder.forBrowser('name'); + builder = builder.forBrowser('name', 'version'); + builder = builder.forBrowser('name', 'version', 'platform'); + + var cap: webdriver.Capabilities = builder.getCapabilities(); + var str:string = builder.getServerUrl(); + + builder = builder.setAlertBehavior('behavior'); + builder = builder.setChromeOptions(new chrome.Options()); + builder = builder.setControlFlow(new webdriver.promise.ControlFlow()); + builder = builder.setEnableNativeEvents(true); + builder = builder.setFirefoxOptions(new firefox.Options()); + builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); + builder = builder.setLoggingPrefs({ "key": "value" }); + builder = builder.setProxy({ proxyType: 'type' }); + builder = builder.setScrollBehavior(1); + builder = builder.usingServer('http://someserver'); + builder = builder.withCapabilities(new webdriver.Capabilities()); + builder = builder.withCapabilities({ something: true }); +} + +function TestActionSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); + + // Click + sequence = sequence.click(); + sequence = sequence.click(webdriver.Button.LEFT); + sequence = sequence.click(element); + sequence = sequence.click(element, webdriver.Button.LEFT); + + // DoubleClick + sequence = sequence.doubleClick(); + sequence = sequence.doubleClick(webdriver.Button.LEFT); + sequence = sequence.doubleClick(element); + sequence = sequence.doubleClick(element, webdriver.Button.LEFT); + + // DragAndDrop + sequence = sequence.dragAndDrop(element, element); + sequence = sequence.dragAndDrop(element, {x: 1, y: 2}); + + // KeyDown + sequence = sequence.keyDown(webdriver.Key.ADD); + + // KeyUp + sequence = sequence.keyUp(webdriver.Key.ADD); + + // MouseDown + sequence = sequence.mouseDown(); + sequence = sequence.mouseDown(webdriver.Button.LEFT); + sequence = sequence.mouseDown(element); + sequence = sequence.mouseDown(element, webdriver.Button.LEFT); + + // MouseMove + sequence = sequence.mouseMove(element); + sequence = sequence.mouseMove({x: 1, y: 1}); + sequence = sequence.mouseMove(element, {x: 1, y: 2}); + + // MouseUp + sequence = sequence.mouseUp(); + sequence = sequence.mouseUp(webdriver.Button.LEFT); + sequence = sequence.mouseUp(element); + sequence = sequence.mouseUp(element, webdriver.Button.LEFT); + + // SendKeys + sequence = sequence.sendKeys("A", "B", "C"); + + sequence.perform().then(function () { }); +} + +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(function () { }); +} + +function TestAlert() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var alert: webdriver.Alert = driver.switchTo().alert(); + + alert.accept().then(function () { }); + alert.dismiss().then(function () { }); + alert.getText().then(function (text: string) { }); + alert.sendKeys("ABC").then(function () { }); +} + +function TestBrowser() { + var browser: string; + + browser = webdriver.Browser.ANDROID; + browser = webdriver.Browser.CHROME; + browser = webdriver.Browser.FIREFOX; + browser = webdriver.Browser.HTMLUNIT; + browser = webdriver.Browser.INTERNET_EXPLORER; + browser = webdriver.Browser.IPAD; + browser = webdriver.Browser.IPHONE; + browser = webdriver.Browser.OPERA; + browser = webdriver.Browser.PHANTOM_JS; + browser = webdriver.Browser.SAFARI; +} + +function TestButton() { + var button: number; + + button = webdriver.Button.LEFT; + button = webdriver.Button.MIDDLE; + button = webdriver.Button.RIGHT; +} + +function TestCapabilities() { + var capabilities: webdriver.Capabilities = new webdriver.Capabilities(); + capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome()); + var objCapabilities: any = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + capabilities = new webdriver.Capabilities(objCapabilities); + + var anything: any = capabilities.get(webdriver.Capability.SECURE_SSL); + var check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL); + capabilities = capabilities.merge(capabilities); + capabilities = capabilities.merge(objCapabilities); + capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); + capabilities = capabilities.set(webdriver.Capability.VERSION, null); + capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); + capabilities = capabilities.setLoggingPrefs({ "key": "value" }); + capabilities = capabilities.setProxy({ proxyType: 'Type' }); + capabilities = capabilities.setEnableNativeEvents(true); + capabilities = capabilities.setScrollBehavior(1); + capabilities = capabilities.setAlertBehavior('accept'); + + anything = capabilities.toJSON(); + + capabilities = webdriver.Capabilities.android(); + capabilities = webdriver.Capabilities.chrome(); + capabilities = webdriver.Capabilities.firefox(); + capabilities = webdriver.Capabilities.htmlunit(); + capabilities = webdriver.Capabilities.htmlunitwithjs(); + capabilities = webdriver.Capabilities.ie(); + capabilities = webdriver.Capabilities.ipad(); + capabilities = webdriver.Capabilities.iphone(); + capabilities = webdriver.Capabilities.opera(); + capabilities = webdriver.Capabilities.phantomjs(); + capabilities = webdriver.Capabilities.safari(); +} + +function TestCapability() { + var capability: string; + + capability = webdriver.Capability.ACCEPT_SSL_CERTS; + capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR; + capability = webdriver.Capability.HANDLES_ALERTS; + capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.NATIVE_EVENTS; + capability = webdriver.Capability.PLATFORM; + capability = webdriver.Capability.PROXY; + capability = webdriver.Capability.ROTATABLE; + capability = webdriver.Capability.SECURE_SSL; + capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; + capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; + capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; + capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; + capability = webdriver.Capability.TAKES_SCREENSHOT; + capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR; + capability = webdriver.Capability.VERSION; +} + +function TestCommand() { + var command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE); + + var name: string = command.getName(); + var param: any = command.getParameter("param"); + + var params: any = command.getParameters(); + + command = command.setParameter("param", 123); + command = command.setParameters({ param: 123 }); +} + +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +} + +function TestCommandName() { + var command: string; + + command = webdriver.CommandName.ACCEPT_ALERT; + command = webdriver.CommandName.ADD_COOKIE; + command = webdriver.CommandName.CLEAR_APP_CACHE; + command = webdriver.CommandName.CLEAR_ELEMENT; + command = webdriver.CommandName.CLEAR_LOCAL_STORAGE; + command = webdriver.CommandName.CLEAR_SESSION_STORAGE; + command = webdriver.CommandName.CLICK; + command = webdriver.CommandName.CLICK_ELEMENT; + command = webdriver.CommandName.CLOSE; + command = webdriver.CommandName.DELETE_ALL_COOKIES; + command = webdriver.CommandName.DELETE_COOKIE; + command = webdriver.CommandName.DESCRIBE_SESSION; + command = webdriver.CommandName.DISMISS_ALERT; + command = webdriver.CommandName.DOUBLE_CLICK; + command = webdriver.CommandName.ELEMENT_EQUALS; + command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT; + command = webdriver.CommandName.EXECUTE_SCRIPT; + command = webdriver.CommandName.EXECUTE_SQL; + command = webdriver.CommandName.FIND_CHILD_ELEMENT; + command = webdriver.CommandName.FIND_CHILD_ELEMENTS; + command = webdriver.CommandName.FIND_ELEMENT; + command = webdriver.CommandName.FIND_ELEMENTS; + command = webdriver.CommandName.GET; + command = webdriver.CommandName.GET_ACTIVE_ELEMENT; + command = webdriver.CommandName.GET_ALERT_TEXT; + command = webdriver.CommandName.GET_ALL_COOKIES; + command = webdriver.CommandName.GET_APP_CACHE; + command = webdriver.CommandName.GET_APP_CACHE_STATUS; + command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES; + command = webdriver.CommandName.GET_COOKIE; + command = webdriver.CommandName.GET_CURRENT_URL; + command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE; + command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE; + command = webdriver.CommandName.GET_ELEMENT_LOCATION; + command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW; + command = webdriver.CommandName.GET_ELEMENT_SIZE; + command = webdriver.CommandName.GET_ELEMENT_TAG_NAME; + command = webdriver.CommandName.GET_ELEMENT_TEXT; + command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY; + command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS; + command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE; + command = webdriver.CommandName.GET_LOCATION; + command = webdriver.CommandName.GET_LOG; + command = webdriver.CommandName.GET_PAGE_SOURCE; + command = webdriver.CommandName.GET_SCREEN_ORIENTATION; + command = webdriver.CommandName.GET_SERVER_STATUS; + command = webdriver.CommandName.GET_SESSION_LOGS; + command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS; + command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE; + command = webdriver.CommandName.GET_SESSIONS; + command = webdriver.CommandName.GET_TITLE; + command = webdriver.CommandName.GET_WINDOW_HANDLES; + command = webdriver.CommandName.GET_WINDOW_POSITION; + command = webdriver.CommandName.GET_WINDOW_SIZE; + command = webdriver.CommandName.GO_BACK; + command = webdriver.CommandName.GO_FORWARD; + command = webdriver.CommandName.IMPLICITLY_WAIT; + command = webdriver.CommandName.IS_BROWSER_ONLINE; + command = webdriver.CommandName.IS_ELEMENT_DISPLAYED; + command = webdriver.CommandName.IS_ELEMENT_ENABLED; + command = webdriver.CommandName.IS_ELEMENT_SELECTED; + command = webdriver.CommandName.MAXIMIZE_WINDOW; + command = webdriver.CommandName.MOUSE_DOWN; + command = webdriver.CommandName.MOUSE_UP; + command = webdriver.CommandName.MOVE_TO; + command = webdriver.CommandName.NEW_SESSION; + command = webdriver.CommandName.QUIT; + command = webdriver.CommandName.REFRESH; + command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SCREENSHOT; + command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT; + command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT; + command = webdriver.CommandName.SET_ALERT_TEXT; + command = webdriver.CommandName.SET_BROWSER_ONLINE; + command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.SET_LOCATION; + command = webdriver.CommandName.SET_SCREEN_ORIENTATION; + command = webdriver.CommandName.SET_SCRIPT_TIMEOUT; + command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SET_TIMEOUT; + command = webdriver.CommandName.SET_WINDOW_POSITION; + command = webdriver.CommandName.SET_WINDOW_SIZE; + command = webdriver.CommandName.SUBMIT_ELEMENT; + command = webdriver.CommandName.SWITCH_TO_FRAME; + command = webdriver.CommandName.SWITCH_TO_WINDOW; + command = webdriver.CommandName.TOUCH_DOUBLE_TAP; + command = webdriver.CommandName.TOUCH_DOWN; + command = webdriver.CommandName.TOUCH_FLICK; + command = webdriver.CommandName.TOUCH_LONG_PRESS; + command = webdriver.CommandName.TOUCH_MOVE; + command = webdriver.CommandName.TOUCH_SCROLL; + command = webdriver.CommandName.TOUCH_SINGLE_TAP; + command = webdriver.CommandName.TOUCH_UP; +} + +function TestEventEmitter() { + var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); + + var callback = function (a: number, b: number, c: number) {}; + + emitter = emitter.addListener('ABC', callback); + emitter = emitter.addListener('ABC', callback, this); + + emitter.emit('ABC', 1, 2, 3); + + var listeners = emitter.listeners('ABC'); + if (listeners[0].oneshot) { + listeners[0].fn.apply(listeners[0].scope); + } + var length: number = listeners.length; + var listenerInfo = listeners[0]; + if (listenerInfo.oneshot) { + listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]); + } + + emitter = emitter.on('ABC', callback); + emitter = emitter.on('ABC', callback, this); + + emitter = emitter.once('ABC', callback); + emitter = emitter.once('ABC', callback, this); + + emitter = emitter.removeListener('ABC', callback); + + emitter.removeAllListeners('ABC'); + emitter.removeAllListeners(); +} + +function TestKey() { + var key: webdriver.Key; + + key = webdriver.Key.ADD; + key = webdriver.Key.ALT; + key = webdriver.Key.ARROW_DOWN; + key = webdriver.Key.ARROW_LEFT; + key = webdriver.Key.ARROW_RIGHT; + key = webdriver.Key.ARROW_UP; + key = webdriver.Key.BACK_SPACE; + key = webdriver.Key.CANCEL; + key = webdriver.Key.CLEAR; + key = webdriver.Key.COMMAND; + key = webdriver.Key.CONTROL; + key = webdriver.Key.DECIMAL; + key = webdriver.Key.DELETE; + key = webdriver.Key.DIVIDE; + key = webdriver.Key.DOWN; + key = webdriver.Key.END; + key = webdriver.Key.ENTER; + key = webdriver.Key.EQUALS; + key = webdriver.Key.ESCAPE; + key = webdriver.Key.F1; + key = webdriver.Key.F2; + key = webdriver.Key.F3; + key = webdriver.Key.F4; + key = webdriver.Key.F5; + key = webdriver.Key.F6; + key = webdriver.Key.F7; + key = webdriver.Key.F8; + key = webdriver.Key.F9; + key = webdriver.Key.F10; + key = webdriver.Key.F11; + key = webdriver.Key.F12; + key = webdriver.Key.HELP; + key = webdriver.Key.HOME; + key = webdriver.Key.INSERT; + key = webdriver.Key.LEFT; + key = webdriver.Key.META; + key = webdriver.Key.MULTIPLY; + key = webdriver.Key.NULL; + key = webdriver.Key.NUMPAD0; + key = webdriver.Key.NUMPAD1; + key = webdriver.Key.NUMPAD2; + key = webdriver.Key.NUMPAD3; + key = webdriver.Key.NUMPAD4; + key = webdriver.Key.NUMPAD5; + key = webdriver.Key.NUMPAD6; + key = webdriver.Key.NUMPAD7; + key = webdriver.Key.NUMPAD8; + key = webdriver.Key.NUMPAD9; + key = webdriver.Key.PAGE_DOWN; + key = webdriver.Key.PAGE_UP; + key = webdriver.Key.PAUSE; + key = webdriver.Key.RETURN; + key = webdriver.Key.RIGHT; + key = webdriver.Key.SEMICOLON; + key = webdriver.Key.SEPARATOR; + key = webdriver.Key.SHIFT; + key = webdriver.Key.SPACE; + key = webdriver.Key.SUBTRACT; + key = webdriver.Key.TAB; + key = webdriver.Key.UP; +} + +function TestBy() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.By = new webdriver.By('class name', 'class'); + + var str: string = locator.toString(); + + locator = webdriver.By.className('class'); + locator = webdriver.By.css('css'); + locator = webdriver.By.id('id'); + locator = webdriver.By.linkText('link'); + locator = webdriver.By.name('name'); + locator = webdriver.By.partialLinkText('text'); + locator = webdriver.By.tagName('tag'); + locator = webdriver.By.xpath('xpath'); + + // Can import "By" without import declarations + var By = webdriver.By; + + var locatorHash: webdriver.ByHash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + + webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); +} + +function TestSession() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var capabilitiesObj: any = {}; + capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID; + capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID'; + session = new webdriver.Session('ABC', capabilitiesObj); + + var capabilities: webdriver.Capabilities = session.getCapabilities(); + var capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME); + var id: string = session.getId(); + var data: string = session.toJSON(); +} + +function TestUnhandledAlertError() { + var someFunc = function (error: webdriver.UnhandledAlertError) { + var baseError: Error = error; + var str: string = error.getAlertText(); + str = error.toString(); + } +} + +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then(function(path: string) {}); +} + +function TestWebDriverLogs() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var logs: webdriver.Logs = new webdriver.Logs(driver); + + logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; + logs.getAvailableLogTypes().then(function (types: string[]) { }); +} + +function TestWebDriverNavigation() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + + navigation.back().then(function () { }); + navigation.forward().then(function () { }); + navigation.refresh().then(function () { }); + navigation.to('http://google.com').then(function () { }); +} + +function TestWebDriverOptions() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var options: webdriver.Options = new webdriver.Options(driver); + var promise: webdriver.promise.Promise; + + // Add Cookie + promise = options.addCookie('name', 'value'); + promise = options.addCookie('name', 'value', 'path'); + promise = options.addCookie('name', 'value', 'path', 'domain'); + promise = options.addCookie('name', 'value', 'path', 'domain', true); + promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); + promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + + promise = options.deleteAllCookies(); + promise = options.deleteCookie('name'); + options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); + options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); + + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); +} + +function TestWebDriverTargetLocator() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var promise: webdriver.promise.Promise; + + var element: webdriver.WebElement = locator.activeElement(); + var alert: webdriver.Alert = locator.alert(); + promise = locator.defaultContent(); + promise = locator.frame(1); + promise = locator.window('nameOrHandle'); +} + +function TestWebDriverTimeouts() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var promise: webdriver.promise.Promise; + + promise = timeouts.implicitlyWait(123); + promise = timeouts.pageLoadTimeout(123); + promise = timeouts.setScriptTimeout(123); +} + +function TestWebDriverWindow() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var window: webdriver.Window = new webdriver.Window(driver); + var locationPromise: webdriver.promise.Promise; + var sizePromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + locationPromise = window.getPosition(); + sizePromise = window.getSize(); + voidPromise = window.maximize(); + voidPromise = window.setPosition(12, 34); + voidPromise = window.setSize(12, 34); +} + +function TestWebDriver() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var sessionPromise: webdriver.promise.Promise; + var executor: webdriver.Executor = executors.createExecutor("http://someserver"); + var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); + var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); + driver = new webdriver.WebDriver(session, executor, flow); + driver = new webdriver.WebDriver(sessionPromise, executor); + driver = new webdriver.WebDriver(sessionPromise, executor, flow); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); + + // call + stringPromise = driver.call(function(){ return 'value'; }); + stringPromise = driver.call(function(){ return stringPromise; }); + stringPromise = driver.call(function(){ var d: any = this; return 'value'; }, driver); + stringPromise = driver.call(function(a: number){ return 'value'; }, driver, 1); + + voidPromise = driver.close(); + flow = driver.controlFlow(); + + // executeAsyncScript + stringPromise = driver.executeAsyncScript('function(){}'); + stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); + stringPromise = driver.executeAsyncScript(function(){}); + stringPromise = driver.executeAsyncScript(function(a: number){}, 1); + + // executeScript + stringPromise = driver.executeScript('function(){}'); + stringPromise = driver.executeScript('function(){}', 1, 2, 3); + stringPromise = driver.executeScript(function(){}); + stringPromise = driver.executeScript(function(a: number){}, 1); + + // findElement + var element: webdriver.WebElement; + element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement(webdriver.By.js('function(){}')); + + // findElements + driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + + voidPromise = driver.get('http://www.google.com'); + driver.getAllWindowHandles().then(function (handles: string[]) { }); + driver.getCapabilities().then(function (caps: webdriver.Capabilities) { }); + stringPromise = driver.getCurrentUrl(); + stringPromise = driver.getPageSource() + driver.getSession().then(function (session: webdriver.Session) { });; + stringPromise = driver.getTitle(); + stringPromise = driver.getWindowHandle(); + + booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + + voidPromise = driver.quit(); + voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + voidPromise = driver.sleep(123); + stringPromise = driver.takeScreenshot(); + + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait(function(driver: webdriver.WebDriver) { return true; }); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + + driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); + driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); +} + +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string|webdriver.promise.IThenable = serializable.serialize(); +} + +function TestWebElement() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var promise: webdriver.promise.Promise; + var element: webdriver.WebElement; + + element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, promise); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + voidPromise = element.clear(); + voidPromise = element.click(); + + element = element.findElement(webdriver.By.id('ABC')); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + + stringPromise = element.getAttribute('class'); + stringPromise = element.getCssValue('display'); + driver = element.getDriver(); + stringPromise = element.getInnerHtml(); + element.getLocation().then(function (location: webdriver.ILocation) { }); + stringPromise = element.getOuterHtml(); + element.getSize().then(function (size: webdriver.ISize) { }); + stringPromise = element.getTagName(); + stringPromise = element.getText(); + booleanPromise = element.isDisplayed(); + booleanPromise = element.isEnabled(); + booleanPromise = element.isSelected(); + voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); + voidPromise = element.submit(); + element.getId().then(function (id: string) { }); + element.getRawId().then(function (id: string) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); + + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); +} + +function TestWebElementPromise() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); + + elementPromise.cancel(); + elementPromise.cancel('reason'); + + var bool: boolean = elementPromise.isPending(); + + elementPromise.then(); + elementPromise.then(function (element: webdriver.WebElement) { }); + elementPromise.then(function (element: webdriver.WebElement) { }, function (error: any) { }); + elementPromise.then(function (element: webdriver.WebElement) { return "foo"; }, function (error: any) { }).then(function (result: string) { }); + + elementPromise.thenCatch(function (error: any) { }).then(function (value: any) { }); + + elementPromise.thenFinally(function () { }); +} + +function TestLogging() { + var preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences(); + preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); + var prefs: any = preferences.toJSON(); + + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + level = webdriver.logging.getLevel(1); + + level = webdriver.logging.Level.ALL; + level = webdriver.logging.Level.DEBUG; + level = webdriver.logging.Level.INFO; + level = webdriver.logging.Level.OFF; + level = webdriver.logging.Level.SEVERE; + level = webdriver.logging.Level.WARNING; + + var name: string = level.name(); + var value: number = level.value(); + + var type: webdriver.logging.Type; + type = webdriver.logging.Type.BROWSER; + type = webdriver.logging.Type.CLIENT; + type = webdriver.logging.Type.DRIVER; + type = webdriver.logging.Type.PERFORMANCE; + type = webdriver.logging.Type.SERVER; +} + +function TestLoggingEntry() { + var entry: webdriver.logging.Entry; + + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC'); + entry = new webdriver.logging.Entry('ALL', 'ABC'); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER); + + var entryObj: any = entry.toJSON(); + + var message: string = entry.message; + var timestamp: number = entry.timestamp; + var type: string = entry.type; +} + +function TestPromiseModule() { + var cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError(); + cancellationError = new webdriver.promise.CancellationError("message"); + var str: string = cancellationError.message; + str = cancellationError.name; + + var stringPromise: webdriver.promise.Promise; + var numberPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); + + webdriver.promise.asap('abc', function(value: any){ return true; }); + webdriver.promise.asap('abc', function(value: any){}, function(err: any) { return 'ABC'; }); + + stringPromise = webdriver.promise.checkedNodeCall(function(err: any, value: any) { return 'abc'; }); + + webdriver.promise.consume(function () { + return 5; + }).then(function (value: number) { }); + webdriver.promise.consume(function () { + return 5; + }, this).then(function (value: number) { }); + webdriver.promise.consume(function (a: number, b: number, c: number) { + return 5; + }, this, 1, 2, 3).then(function (value: number) { }); + + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + return true; + }, this); + + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + return true; + }, this); + + var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); + + stringPromise = webdriver.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { return 'ABC' }); + + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); + + stringPromise = deferred.promise; + + deferred.fulfill('ABC'); + deferred.reject('error'); + + voidPromise = webdriver.promise.delayed(123); + + voidPromise = webdriver.promise.fulfilled(); + stringPromise = webdriver.promise.fulfilled('abc'); + + stringPromise = webdriver.promise.fullyResolved('abc'); + + var bool: boolean = webdriver.promise.isGenerator(function () { }); + var isPromise: boolean = webdriver.promise.isPromise('ABC'); + + stringPromise = webdriver.promise.rejected('{a: 123}'); + + webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); +} + +function TestUntilModule() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; + + conditionB = webdriver.until.ableToSwitchToFrame(5); + var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); + conditionB = webdriver.until.elementIsDisabled(el); + conditionB = webdriver.until.elementIsEnabled(el); + conditionB = webdriver.until.elementIsNotSelected(el); + conditionB = webdriver.until.elementIsNotVisible(el); + conditionB = webdriver.until.elementIsSelected(el); + conditionB = webdriver.until.elementIsVisible(el); + conditionB = webdriver.until.elementTextContains(el, 'text'); + conditionB = webdriver.until.elementTextIs(el, 'text'); + conditionB = webdriver.until.elementTextMatches(el, /text/); + conditionB = webdriver.until.stalenessOf(el); + conditionB = webdriver.until.titleContains('text'); + conditionB = webdriver.until.titleIs('text'); + conditionB = webdriver.until.titleMatches(/text/); + + conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); +} + +function TestControlFlow() { + var flow: webdriver.promise.ControlFlow; + flow = new webdriver.promise.ControlFlow(); + + var emitter: webdriver.EventEmitter = flow; + + var eventType: string; + + eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.RESET; + eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; + eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; + + var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(function() { return 'value'; }); + stringPromise = flow.execute(function() { return stringPromise; }); + stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); + + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); + + flow.reset(); + + var voidPromise: webdriver.promise.Promise = flow.timeout(123); + voidPromise = flow.timeout(123, 'Description'); + + stringPromise = flow.wait(stringPromise); + + voidPromise = flow.wait(function() { return true; }); + voidPromise = flow.wait(function() { return true; }, 123); + voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); +} + +function TestDeferred() { + var deferred: webdriver.promise.Deferred; + + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(new webdriver.promise.ControlFlow()); + + var promise: webdriver.promise.Promise = deferred.promise; + + deferred.errback(new Error('Error')); + deferred.errback('Error'); + deferred.fulfill('abc'); + deferred.reject(new Error('Error')); + deferred.reject('Error'); + deferred.removeAll(); +} + +function TestPromiseClass() { + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: webdriver.promise.Promise)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }, controlFlow); + + promise.cancel('Abort'); + + var isPending: boolean = promise.isPending(); + + promise = promise.then(); + promise = promise.then(function( a: string ) { return 'cde'; }); + promise = promise.then(function( a: string ) { return 'cde'; }, function( e: any) {}); + promise = promise.then(function( a: string ) { return 'cde'; }, function (e: any) { return 123; }); + + promise = promise.thenCatch(function (error: any) { }); + + promise.thenFinally(function () { }); +} + +function TestThenableClass() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); + + thenable.cancel('Abort'); + + var isPending: boolean = thenable.isPending(); + + thenable = thenable.then(function (a: string) { return 'cde'; }); + thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); + thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); + + thenable = thenable.thenCatch(function (error: any) { }); + + thenable.thenFinally(function () { }); +} + +function TestErrorCode() { + var errorCode: number; + + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); +} + +function TestTestingModule() { + testing.before(function () { + }); + + testing.beforeEach(function () { + }); + + testing.describe("My test suite", function () { + testing.it("My test", function () { + }); + + testing.iit("My exclusive test.", function () { + }); + + }); + + testing.xdescribe("My disabled suite", function () { + testing.xit("My disabled test.", function () { + }); + }); + + testing.after(function () { + }); + + testing.afterEach(function () { + }); +} diff --git a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts similarity index 60% rename from selenium-webdriver/selenium-webdriver-2.44.0.d.ts rename to selenium-webdriver/selenium-webdriver-2.53.1.d.ts index 548048b695..a6e419755d 100644 --- a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts +++ b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selenium WebDriverJS 2.44.0 -// Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.53.1 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { setChromeLogFile(path: string): Options; + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + function getDefaultService(): remote.DriverService; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: any): void; + function setDefaultService(service: remote.DriverService): void; } -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); +declare namespace edge { - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string): Options; - setProfile(profile: Profile): Options; + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string): Options; - setBinary(binary: Binary): Options; + /** + * Sets the page load strategy for Edge. + * Supported values are "normal", "eager", and "none"; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; } + + /** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. */ - function createExecutor(url: string): webdriver.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string|any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string|any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; + } + + /** + * @return {string} . + * @throws {Error} + */ + function findWires(): string; + + /** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ + function createWiresService(binary: string|any): remote.DriverService; + + /** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ + function prepareProfile(profile: string|any, port: number): any; + + /** + * A WebDriver client for Firefox. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace http { + /** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ + function headersToString(headers: any): string; + + /** + * Represents a HTTP request message. This class is a "partial" request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ + class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; + } + + /** + * Represents a HTTP response message. + * @final + */ + class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; + } + + + function post(path: string): any; + function del(path: string): any; + function get(path: string): any; + function resource(method: string, path: string): any; + + /** + * A basic HTTP client used to send messages to a remote end. + */ + class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; + } + + /** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ + function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + + /** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ + class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ":" will be replaced by the parameter of the + * same name. For example, given "/person/:name" and the parameters + * "{name: 'Bob'}", the final command path will be "/person/Bob". + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * "/path/:variable/segment". + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; + } + + /** + * @param {string} str . + * @return {?} . + */ + function tryParse(str: string): any; + + /** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ + function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + + /** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ + function buildPath(path: string, parameters: Object): string; +} + +declare namespace ie { + + /** + * A WebDriver client for Microsoft's Internet Explorer. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing IEDriver specific options. + */ + class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only "best effort" support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only "best effort" support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + +} + +declare namespace opera { + /** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): any; + + /** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ + class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: Array): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace remote { + /** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ + interface ServiceOptions {} + + /** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ + class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; + } +} + +declare namespace safari { + class Server {} + + /** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ + function findSafariExecutable(): any; + + /** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ + function createConnectFile(serverUrl: string): any; + + /** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ + function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + + /** @return {string} . */ + function getRandomString(): string; + + /** + * @implements {command.Executor} + */ + class CommandExecutor { + } + + /** + * Configuration options specific to the {@link Driver SafariDriver}. + */ + class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + + } } declare namespace webdriver { namespace error { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: string); + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Static Properties + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: string; - }; + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @type {string} */ - state: string; + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - message: string; + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - name: string; + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - stack: string; + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): string; + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + enum Type { + /** Logs originating from the browser. */ + BROWSER, + /** Logs from a WebDriver client. */ + CLIENT, + /** Logs from a WebDriver implementation. */ + DRIVER, + /** Logs related to performance. */ + PERFORMANCE, + /** Logs from the remote server. */ + SERVER + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** This logger's name. */ + name(): string; + + /** The numeric log level. */ + value(): number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } /** * Converts a level name or value to a {@link webdriver.logging.Level} value. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, "foo" is considered the parent of + * the "foo.bar" and an ancestor of "foo.bar.baz". + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; - //region Methods + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; - //endregion + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string|Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @return {!ManagedPromise>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - *

If the return value of the filter function is a promise, this function + * If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - *

If the filter function throws or returns a rejected promise, the promise + * If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - *

If the return value of the mapping function is a promise, this function + * If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - *

If the mapping function throws or returns a rejected promise, the + * If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - *

Example 1: the Fibonacci Sequence. - *


-         * webdriver.promise.consume(function* fibonacci() {
-         *   var n1 = 1, n2 = 1;
-         *   for (var i = 0; i < 4; ++i) {
-         *     var tmp = yield n1 + n2;
-         *     n1 = n2;
-         *     n2 = tmp;
-         *   }
-         *   return n1 + n2;
-         * }).then(function(result) {
-         *   console.log(result);  // 13
-         * });
-         * 
+ * __Example 1:__ the Fibonacci Sequence. * - *

Example 2: a generator that throws. - *


-         * webdriver.promise.consume(function* () {
-         *   yield webdriver.promise.delayed(250).then(function() {
-         *     throw Error('boom');
-         *   });
-         * }).thenCatch(function(e) {
-         *   console.log(e.toString());  // Error: boom
-         * });
-         * 
+ * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); * * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @return {!ManagedPromise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); } interface IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } catch (ex) {
-             *     console.error(ex);
-             *   }
              *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenCatch(function(ex) {
-             *     console.error(ex);
-             *   });
-             * 
+ * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } finally {
-             *     cleanUp();
-             *   }
-             *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenFinally(cleanUp);
-             * 
- * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *

-             *   try {
-             *     throw Error('one');
-             *   } finally {
-             *     throw Error('two');  // Hides Error: one
-             *   }
-             *
-             *   webdriver.promise.rejected(Error('one'))
-             *       .thenFinally(function() {
-             *         throw Error('two');  // Hides Error: one
-             *       });
-             * 
- * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): Promise; + catch(errback: Function): Promise; } /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ class Thenable implements IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } catch (ex) {
-             *     console.error(ex);
-             *   }
              *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenCatch(function(ex) {
-             *     console.error(ex);
-             *   });
-             * 
+ * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - + catch(errback: Function): Promise; /** * Registers a listener to invoke when this promise is resolved, regardless * of whether the promise's value was successfully computed. This function * is synonymous with the {@code finally} clause in a synchronous API: - *

-             *   // Synchronous API:
-             *   try {
-             *     doSynchronousWork();
-             *   } finally {
-             *     cleanUp();
-             *   }
              *
-             *   // Asynchronous promise API:
-             *   doAsynchronousWork().thenFinally(cleanUp);
-             * 
+ * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered * callback returns a rejected promise or throws an error, it will silently * replace the rejection error (if any) from this promise: - *

-             *   try {
-             *     throw Error('one');
-             *   } finally {
-             *     throw Error('two');  // Hides Error: one
-             *   }
              *
-             *   webdriver.promise.rejected(Error('one'))
-             *       .thenFinally(function() {
-             *         throw Error('two');  // Hides Error: one
-             *       });
-             * 
+ * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + finally(callback: Function): Promise; /** * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function will - * also ensure the prototype's {@code then} function is exported from compiled - * code. - * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The * constructor whose prototype to modify. */ static addImplementation(ctor: Function): void; - /** - * Checks if an object has been tagged for implementing the Thenable interface - * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. * @param {*} object The object to test. * @return {boolean} Whether the object is an implementation of the Thenable * interface. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * function((T|IThenable|Thenable)=), * function(*=))} resolver * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback functions, - * one for fulfilling the promise and another for rejecting it. - * @param {promise.ControlFlow=} opt_flow The control flow + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow * this instance was created under. Defaults to the currently active flow. - * @constructor - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + /** * Registers a listener to invoke when this promise is resolved, regardless @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
    - *
  1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
  3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
+ * to the designated frame. The target frame may be specified as * - *

Upon successful resolution of this condition, the driver will be left + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {number} + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: string; + enum Key { + NULL, + CANCEL, // ^break + HELP, + BACK_SPACE, + TAB, + CLEAR, + RETURN, + ENTER, + SHIFT, + CONTROL, + ALT, + PAUSE, + ESCAPE, + SPACE, + PAGE_UP, + PAGE_DOWN, + END, + HOME, + ARROW_LEFT, + LEFT, + ARROW_UP, + UP, + ARROW_RIGHT, + RIGHT, + ARROW_DOWN, + DOWN, + INSERT, + DELETE, + SEMICOLON, + EQUALS, - NUMPAD0: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

Example:


-     *   new webdriver.ActionSequence(driver).
-     *       keyDown(webdriver.Key.SHIFT).
-     *       click(element1).
-     *       click(element2).
-     *       dragAndDrop(element3, element4).
-     *       keyUp(webdriver.Key.SHIFT).
-     *       perform();
-     * 
+ * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in pixels. - * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./webdriver.WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. */ - mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - *

If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

sequence.mouseMove(element).mouseDown()
* - *

Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - *

If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

sequence.mouseMove(element).mouseUp()
* - *

Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * @param {!webdriver.WebElement} element The element to drag. - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in pixels. - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {!./webdriver.WebElement} element The element to drag. + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; /** * Clicks a mouse button. * - *

If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

sequence.mouseMove(element).click()
* - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * sequence.mouseMove(element).click() + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Double-clicks a mouse button. * - *

If an element is provided, the mouse will first be moved to the center of + * If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: - *

sequence.mouseMove(element).doubleClick()
* - *

Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } - interface IOffset { x: number; y: number; } - interface ISpeed { xspeed: number; yspeed: number; } - /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - interface Alert { + class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); //region Methods @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): webdriver.promise.Promise; + /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -2580,47 +3543,27 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - *


+     *
      *     driver.switchTo().alert().dismiss();
      *     driver.switchTo().alert().then(function(alert) {
      *       return alert.dismiss();
      *     });
-     * 
* - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + class AlertPromise extends Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: webdriver.promise.Promise); } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3573,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3596,45 @@ declare namespace webdriver { noProxy?: string; } + /** + * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new webdriver.Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ class Builder { //region Constructors @@ -2664,15 +3648,45 @@ declare namespace webdriver { //region Methods + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + /** * Creates a new WebDriver client based on this builder's current * configuration. * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() */ build(): WebDriver; + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): webdriver.promise.Promise; + /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -2705,6 +3719,12 @@ declare namespace webdriver { */ getServerUrl(): string; + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -2735,6 +3755,17 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -2753,6 +3784,16 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -2760,17 +3801,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + setProxy(config: webdriver.ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -2793,6 +3854,16 @@ declare namespace webdriver { */ usingServer(url: string): Builder; + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -2800,12 +3871,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + withCapabilities(capabilities: Object|Capabilities): Builder; //endregion } + /** + * Describes a mechanism for locating an element on the page. + * @final + */ + class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id="$ID"]`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./webdriver.WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; + } + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type ByHash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + /** * Common webdriver capability keys. * @enum {string} @@ -2876,7 +4084,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4118,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4134,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4152,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4214,11 @@ declare namespace webdriver { */ static chrome(): Capabilities; + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -3183,6 +4392,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4452,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): webdriver.promise.Promise + } + + /** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ + class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: webdriver.promise.Promise); + } + + /** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ + class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); } /** @@ -3283,39 +4522,42 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private */ - addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; + /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + once(type: string, fn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4582,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * webdriver.navigate() + * + * @see WebDriver#navigate() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4645,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4665,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as - * a number, should be in milliseconds since midnight, January 1, 1970 UTC. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3467,19 +4715,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4735,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4797,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4805,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4860,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4868,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +4888,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +4903,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +4911,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +4935,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

- * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

- * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

- * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. */ - frame(nameOrIndex: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). - *

- * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. */ alert(): AlertPromise; @@ -3789,27 +5040,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. - * @constructor */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5055,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. */ - static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5090,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5135,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *


-         *   driver.actions().
-         *       mouseDown(element1).
-         *       mouseMove(element2).
-         *       mouseUp().
-         *       perform();
-         * 
- * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5159,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5201,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5418,27 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5447,36 @@ declare namespace webdriver { * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: - *
    - *
  1. Entire page - *
  2. Current window - *
  3. Visible portion of the current frame - *
  4. The screenshot of the entire display containing the browser - *
* - * @return {!webdriver.promise.Promise.} A promise that will be + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -4256,45 +5485,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T|webdriver.promise.IThenable; + [ELEMENT:string]: string; } /** @@ -4554,7 +5763,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5774,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5785,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5808,6 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } - /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -4626,35 +5833,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. */ - constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. */ - static Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. */ - static ELEMENT_KEY: string; + static extractId(obj: IWebElementId): string; + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): WebDriver; + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; /** * Schedule a command to find a descendant of this element. If the element @@ -4688,35 +5919,40 @@ declare namespace webdriver { * }); * } * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +5963,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * promsieinstance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -4799,7 +6035,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6121,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6136,18 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -4907,25 +6155,6 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4933,14 +6162,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6189,14 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -5075,191 +6306,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} contains the given substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector {@code "//div"}, WebDriver will search from the - * document root regardless of whether the locator was used with a - * WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6346,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6360,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6446,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 1ab39ba02a..345a8efc5b 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ function TestChromeDriver() { var driver: chrome.Driver = new chrome.Driver(); driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,6 +31,7 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); + var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -51,7 +52,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); + chrome.setDefaultService({}); } function TestBinary() { @@ -65,8 +66,8 @@ function TestBinary() { function TestFirefoxDriver() { var driver: firefox.Driver = new firefox.Driver(); - driver = new firefox.Driver(webdriver.Capabilities.firefox()); - driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.firefox()); + driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -81,6 +82,7 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); + var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -106,7 +108,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.Executor = executors.createExecutor("url"); + var exec: webdriver.CommandExecutor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -142,9 +144,7 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); - var promise: webdriver.promise.Promise; - element = new webdriver.WebElement(driver, promise); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); // Click sequence = sequence.click(); @@ -187,6 +187,7 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); + sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -195,7 +196,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -318,9 +319,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestDeferredExecutor() { - var promise: webdriver.promise.Promise; - var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +function TestCommandExecutor() { + var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; + c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); } function TestCommandName() { @@ -457,7 +458,7 @@ function TestEventEmitter() { } function TestKey() { - var key: webdriver.Key; + var key: string; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -519,15 +520,35 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; + + key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestBy() { +function TestLocator() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.By = new webdriver.By('class name', 'class'); + var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locatorOrFn: webdriver.Locator|Function; + + locatorOrFn = webdriver.Locator.Strategy.className; + locatorOrFn = webdriver.Locator.Strategy.css; + locatorOrFn = webdriver.Locator.Strategy.id; + locatorOrFn = webdriver.Locator.Strategy.js; + locatorOrFn = webdriver.Locator.Strategy.linkText; + locatorOrFn = webdriver.Locator.Strategy.name; + locatorOrFn = webdriver.Locator.Strategy.partialLinkText; + locatorOrFn = webdriver.Locator.Strategy.tagName; + locatorOrFn = webdriver.Locator.Strategy.xpath; + + locatorOrFn = webdriver.Locator.checkLocator(locator); + locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); + locatorOrFn = webdriver.Locator.checkLocator(Error); + + var using: string = locator.using; + var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -542,7 +563,7 @@ function TestBy() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.ByHash; + var locatorHash: webdriver.By.Hash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -570,7 +591,9 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: Error = error; + var baseError: webdriver.error.Error = error; + + var alert: webdriver.Alert = error.getAlert(); var str: string = error.getAlertText(); str = error.toString(); } @@ -591,7 +614,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.Logs = new webdriver.Logs(driver); + var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; logs.getAvailableLogTypes().then(function (types: string[]) { }); @@ -602,7 +625,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -615,7 +638,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.Options = new webdriver.Options(driver); + var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -631,9 +654,9 @@ function TestWebDriverOptions() { options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); - var logs: webdriver.Logs = options.logs(); - var timeouts: webdriver.Timeouts = options.timeouts(); - var window: webdriver.Window = options.window(); + var logs: webdriver.WebDriverLogs = options.logs(); + var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); + var window: webdriver.WebDriverWindow = options.window(); } function TestWebDriverTargetLocator() { @@ -641,12 +664,13 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); var promise: webdriver.promise.Promise; var element: webdriver.WebElement = locator.activeElement(); var alert: webdriver.Alert = locator.alert(); promise = locator.defaultContent(); + promise = locator.frame('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -656,7 +680,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -669,7 +693,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.Window = new webdriver.Window(driver); + var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -684,7 +708,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.Executor = executors.createExecutor("http://someserver"); + var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -722,11 +746,15 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); + element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -738,11 +766,13 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.Options = driver.manage(); - var navigation: webdriver.Navigation = driver.navigate(); - var locator: webdriver.TargetLocator = driver.switchTo(); + var options: webdriver.WebDriverOptions = driver.manage(); + var navigation: webdriver.WebDriverNavigation = driver.navigate(); + var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); driver.setFileDetector(fileDetector); @@ -765,7 +795,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.IThenable = serializable.serialize(); + var serial: string|webdriver.promise.Promise = serializable.serialize(); } function TestWebElement() { @@ -773,10 +803,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -787,8 +817,13 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); + element = element.findElement({id: 'ABC'}); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -805,11 +840,14 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: string) { }); + element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: webdriver.IWebElementId) { }); + element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); + + var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; + var key: string = webdriver.WebElement.ELEMENT_KEY; } function TestWebElementPromise() { @@ -839,7 +877,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -849,10 +887,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name(); - var value: number = level.value(); + var name: string = level.name; + var value: number = level.value; - var type: webdriver.logging.Type; + var type: string; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -875,6 +913,9 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; + + entry = webdriver.logging.Entry.fromClosureLogRecord({}); + entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -905,29 +946,29 @@ function TestPromiseModule() { return 5; }, this, 1, 2, 3).then(function (value: number) { }); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }, this); @@ -954,13 +995,26 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - stringPromise = webdriver.promise.rejected('{a: 123}'); + voidPromise = webdriver.promise.rejected({a: 123}); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); } +function TestStacktraceModule() { + var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; + + var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); + var baseFrame: webdriver.stacktrace.Frame = frame; + + var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); + var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; + + var err: Error = webdriver.stacktrace.format(new Error("Error")); + var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); +} + function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1071,12 +1125,13 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); + var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); + thenable = thenable.then(); thenable = thenable.then(function (a: string) { return 'cde'; }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); @@ -1089,30 +1144,76 @@ function TestThenableClass() { function TestErrorCode() { var errorCode: number; - errorCode = new webdriver.error.ElementNotSelectableError().code(); - errorCode = new webdriver.error.ElementNotVisibleError().code(); - errorCode = new webdriver.error.InvalidArgumentError().code(); - errorCode = new webdriver.error.InvalidCookieDomainError().code(); - errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); - errorCode = new webdriver.error.InvalidElementStateError().code(); - errorCode = new webdriver.error.InvalidSelectorError().code(); - errorCode = new webdriver.error.NoSuchSessionError().code(); - errorCode = new webdriver.error.JavascriptError().code(); - errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); - errorCode = new webdriver.error.NoSuchAlertError().code(); - errorCode = new webdriver.error.NoSuchElementError().code(); - errorCode = new webdriver.error.NoSuchFrameError().code(); - errorCode = new webdriver.error.NoSuchWindowError().code(); - errorCode = new webdriver.error.ScriptTimeoutError().code(); - errorCode = new webdriver.error.SessionNotCreatedError().code(); - errorCode = new webdriver.error.StaleElementReferenceError().code(); - errorCode = new webdriver.error.TimeoutError().code(); - errorCode = new webdriver.error.UnableToSetCookieError().code(); - errorCode = new webdriver.error.UnableToCaptureScreenError().code(); - errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); - errorCode = new webdriver.error.UnknownCommandError().code(); - errorCode = new webdriver.error.UnknownMethodError().code(); - errorCode = new webdriver.error.UnsupportedOperationError().code(); + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; + errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; + errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; + errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; + errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; + errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; + errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; + errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; + errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; + errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; + errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; + errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; + errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; + errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; + errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; + errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; + errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; + errorCode = webdriver.error.ErrorCode.SUCCESS; + errorCode = webdriver.error.ErrorCode.TIMEOUT; + errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; + errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; + errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; + errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; + errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; +} + +function TestError() { + var error: webdriver.error.Error; + + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); + + var code: number = error.code; + var state: string = error.state; + var message: string = error.message; + var name: string = error.name; + var stack: string = error.stack; + var isAutomationError: boolean = error.isAutomationError; + var errorStr: string = error.toString(); + + state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE + state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; + state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; + state = webdriver.error.Error.State.IME_NOT_AVAILABLE; + state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; + state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; + state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; + state = webdriver.error.Error.State.INVALID_SELECTOR; + state = webdriver.error.Error.State.JAVASCRIPT_ERROR; + state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; + state = webdriver.error.Error.State.NO_SUCH_ALERT; + state = webdriver.error.Error.State.NO_SUCH_DOM + state = webdriver.error.Error.State.NO_SUCH_ELEMENT; + state = webdriver.error.Error.State.NO_SUCH_FRAME; + state = webdriver.error.Error.State.NO_SUCH_WINDOW; + state = webdriver.error.Error.State.SCRIPT_TIMEOUT; + state = webdriver.error.Error.State.SESSION_NOT_CREATED; + state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; + state = webdriver.error.Error.State.SUCCESS; + state = webdriver.error.Error.State.TIMEOUT; + state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; + state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN + state = webdriver.error.Error.State.UNKNOWN_COMMAND; + state = webdriver.error.Error.State.UNKNOWN_ERROR; + state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; } function TestTestingModule() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b3afe098ac..e1301d5b58 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selenium WebDriverJS 2.53.1 -// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,7 +19,8 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -239,53 +240,6 @@ declare namespace chrome { setChromeLogFile(path: string): Options; - /** - * Sets the directory to store Chrome minidumps in. This option is only - * supported when ChromeDriver is running on Linux. - * @param {string} path The directory path. - * @return {!Options} A self reference. - */ - setChromeMinidumpPath(path: string): Options; - - - /** - * Configures Chrome to emulate a mobile device. For more information, refer - * to the ChromeDriver project page on [mobile emulation][em]. Configuration - * options include: - * - * - `deviceName`: The name of a pre-configured [emulated device][devem] - * - `width`: screen width, in pixels - * - `height`: screen height, in pixels - * - `pixelRatio`: screen pixel ratio - * - * __Example 1: Using a Pre-configured Device__ - * - * let options = new chrome.Options().setMobileEmulation( - * {deviceName: 'Google Nexus 5'}); - * - * let driver = new chrome.Driver(options); - * - * __Example 2: Using Custom Screen Configuration__ - * - * let options = new chrome.Options().setMobileEmulation({ - * width: 360, - * height: 640, - * pixelRatio: 3.0 - * }); - * - * let driver = new chrome.Driver(options); - * - * - * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation - * [devem]: https://developer.chrome.com/devtools/docs/device-mode - * - * @param {?({deviceName: string}| - * {width: number, height: number, pixelRatio: number})} config The - * mobile emulation configuration, or `null` to disable emulation. - * @return {!Options} A self reference. - */ - setMobileEmulation(config: any): Options; - /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -301,6 +255,21 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; } /** @@ -379,7 +348,8 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string|Array): ServiceBuilder; + setStdio(config: string): ServiceBuilder; + setStdio(config: any[]): ServiceBuilder; /** @@ -398,7 +368,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): remote.DriverService; + build(): any; } /** @@ -407,1325 +377,395 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): remote.DriverService; + function getDefaultService(): any; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: remote.DriverService): void; + function setDefaultService(service: any): void; } -declare namespace edge { +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@linkplain #getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; } /** - * Class for managing MicrosoftEdgeDriver specific options. + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. */ class Options { + /** + * @constructor + */ + constructor(); - /** - * Extracts the MicrosoftEdgeDriver specific options from the given - * capabilities object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The MicrosoftEdgeDriver options. - */ - static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string): Options; + setProfile(profile: Profile): Options; - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the page load strategy for Edge. - * Supported values are "normal", "eager", and "none"; - * - * @param {string} pageLoadStrategy The page load strategy to use. - * @return {!Options} A self reference. - */ - setPageLoadStrategy(pageLoadStrategy: string): Options; + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string): Options; + setBinary(binary: Binary): Options; - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; } /** - * Creates {@link remote.DriverService} instances that manage a - * MicrosoftEdgeDriver server in a child process. + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the MicrosoftEdgeDriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the - * MicrosoftEdgeDriver cannot be found on the PATH. - */ - constructor(opt_exe?: string); + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string|Array): ServiceBuilder; + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; - /** - * Sets the port to start the MicrosoftEdgeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; } - - /** - * Returns the default MicrosoftEdgeDriver service. If such a service has - * not been configured, one will be constructed using the default configuration - * for an MicrosoftEdgeDriver executable found on the system PATH. - * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Sets the default service to use for new MicrosoftEdgeDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param {(string|!promise.Promise)} url The server's URL, - * or a promise that will resolve to that URL. - * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the - * client to use. - * @returns {!./lib/command.Executor} The new command executor. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. */ - function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; -} - -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); - - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. - */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); - - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; - - - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; - - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; - } - - /** - * Configuration options for the FirefoxDriver. - */ - class Options { - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string|any): Options; - - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string|any): Options; - - /** - * Sets the logging preferences for the new session. - * @param {logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the proxy to use. - * - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Sets whether to use Mozilla's Marionette to drive the browser. - * - * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver - */ - useMarionette(marionette: any): Options; - - /** - * Converts these options to a {@link capabilities.Capabilities} instance. - * - * @return {!capabilities.Capabilities} A new capabilities object. - */ - toCapabilities(): webdriver.Capabilities; - } - - /** - * @return {string} . - * @throws {Error} - */ - function findWires(): string; - - /** - * @param {(string|!Binary)} binary . - * @return {!remote.DriverService} . - */ - function createWiresService(binary: string|any): remote.DriverService; - - /** - * @param {(Profile|string)} profile The profile to prepare. - * @param {number} port The port the FirefoxDriver should listen on. - * @return {!Promise} a promise for the path to the profile directory. - */ - function prepareProfile(profile: string|any, port: number): any; - - /** - * A WebDriver client for Firefox. - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(Options|capabilities.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash - * object. - * @param {promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - */ - constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } -} - -declare namespace http { - /** - * Converts a headers map to a HTTP header block string. - * @param {!Map} headers The map to convert. - * @return {string} The headers as a string. - */ - function headersToString(headers: any): string; - - /** - * Represents a HTTP request message. This class is a "partial" request and only - * defines the path on the server to send a request to. It is each client's - * responsibility to build the full URL for the final request. - * @final - */ - class HttpRequest { - /** - * @param {string} method The HTTP method to use for the request. - * @param {string} path The path on the server to send the request to. - * @param {Object=} opt_data This request's non-serialized JSON payload data. - */ - constructor(method: string, path: string, opt_data?: Object); - - /** @override */ - toString(): string; - } - - /** - * Represents a HTTP response message. - * @final - */ - class HttpResponse { - /** - * @param {number} status The response code. - * @param {!Object} headers The response headers. All header names - * will be converted to lowercase strings for consistent lookups. - * @param {string} body The response body. - */ - constructor(status: number, headers: Object, body: string); - - /** @override */ - toString(): string; - } - - - function post(path: string): any; - function del(path: string): any; - function get(path: string): any; - function resource(method: string, path: string): any; - - /** - * A basic HTTP client used to send messages to a remote end. - */ - class HttpClient { - /** - * @param {string} serverUrl URL for the WebDriver server to send commands to. - * @param {http.Agent=} opt_agent The agent to use for each request. - * Defaults to `http.globalAgent`. - * @param {?string=} opt_proxy The proxy to use for the connection to the - * server. Default is to use no proxy. - */ - constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); - - /** - * Sends a request to the server. The client will automatically follow any - * redirects returned by the server, fulfilling the returned promise with the - * final response. - * - * @param {!HttpRequest} httpRequest The request to send. - * @return {!promise.Promise} A promise that will be fulfilled - * with the server's response. - */ - send(httpRequest: HttpRequest): webdriver.promise.Promise; - } - - /** - * Sends a single HTTP request. - * @param {!Object} options The request options. - * @param {function(!HttpResponse)} onOk The function to call if the - * request succeeds. - * @param {function(!Error)} onError The function to call if the request fails. - * @param {?string=} opt_data The data to send with the request. - * @param {?string=} opt_proxy The proxy server to use for the request. - */ - function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; - - /** - * A command executor that communicates with the server using HTTP + JSON. - * - * By default, each instance of this class will use the legacy wire protocol - * from [Selenium project][json]. The executor will automatically switch to the - * [W3C wire protocol][w3c] if the remote end returns a compliant response to - * a new session command. - * - * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol - * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html - * - * @implements {cmd.Executor} - */ - class Executor { - /** - * @param {!HttpClient} client The client to use for sending requests to the - * server. - */ - constructor(client: HttpClient); - - /** - * Defines a new command for use with this executor. When a command is sent, - * the {@code path} will be preprocessed using the command's parameters; any - * path segments prefixed with ":" will be replaced by the parameter of the - * same name. For example, given "/person/:name" and the parameters - * "{name: 'Bob'}", the final command path will be "/person/Bob". - * - * @param {string} name The command name. - * @param {string} method The HTTP method to use when sending this command. - * @param {string} path The path to send the command to, relative to - * the WebDriver server's command root and of the form - * "/path/:variable/segment". - */ - defineCommand(name: string, method: string, path: string): void; - - /** @override */ - execute(command: any): any; - } - - /** - * @param {string} str . - * @return {?} . - */ - function tryParse(str: string): any; - - /** - * Callback used to parse {@link HttpResponse} objects from a - * {@link HttpClient}. - * @param {!HttpResponse} httpResponse The HTTP response to parse. - * @param {boolean} w3c Whether the response should be processed using the - * W3C wire protocol. - * @return {{value: ?}} The parsed response. - * @throws {WebDriverError} If the HTTP response is an error. - */ - function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; - - /** - * Builds a fully qualified path using the given set of command parameters. Each - * path segment prefixed with ':' will be replaced by the value of the - * corresponding parameter. All parameters spliced into the path will be - * removed from the parameter map. - * @param {string} path The original resource path. - * @param {!Object<*>} parameters The parameters object to splice into the path. - * @return {string} The modified path. - */ - function buildPath(path: string, parameters: Object): string; -} - -declare namespace ie { - - /** - * A WebDriver client for Microsoft's Internet Explorer. - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {promise.ControlFlow=} opt_flow The control flow to use, - * or {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } - - /** - * Class for managing IEDriver specific options. - */ - class Options { - constructor(); - - /** - * Extracts the IEDriver specific options from the given capabilities - * object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The IEDriver options. - */ - static fromCapabilities(caps: webdriver.Capabilities): Options; - - /** - * Whether to disable the protected mode settings check when the session is - * created. Disbling this setting may lead to significant instability as the - * browser may become unresponsive/hang. Only "best effort" support is provided - * when using this capability. - * - * For more information, refer to the IEDriver's - * [required system configuration](http://goo.gl/eH0Yi3). - * - * @param {boolean} ignoreSettings Whether to ignore protected mode settings. - * @return {!Options} A self reference. - */ - introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; - - /** - * Indicates whether to skip the check that the browser's zoom level is set to - * 100%. - * - * @param {boolean} ignore Whether to ignore the browser's zoom level settings. - * @return {!Options} A self reference. - */ - ignoreZoomSetting(ignore: boolean): Options; - - /** - * Sets the initial URL loaded when IE starts. This is intended to be used with - * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in - * the proper Protected Mode zone. Setting this option may cause browser - * instability or flaky and unresponsive code. Only "best effort" support is - * provided when using this option. - * - * @param {string} url The initial browser URL. - * @return {!Options} A self reference. - */ - initialBrowserUrl(url: string): Options; - - /** - * Configures whether to enable persistent mouse hovering (true by default). - * Persistent hovering is achieved by continuously firing mouse over events at - * the last location the mouse cursor has been moved to. - * - * @param {boolean} enable Whether to enable persistent hovering. - * @return {!Options} A self reference. - */ - enablePersistentHover(enable: boolean): Options; - - /** - * Configures whether the driver should attempt to remove obsolete - * {@linkplain webdriver.WebElement WebElements} from its internal cache on - * page navigation (true by default). Disabling this option will cause the - * driver to run with a larger memory footprint. - * - * @param {boolean} enable Whether to enable element reference cleanup. - * @return {!Options} A self reference. - */ - enableElementCacheCleanup(enable: boolean): Options; - - /** - * Configures whether to require the IE window to have input focus before - * performing any user interactions (i.e. mouse or keyboard events). This - * option is disabled by default, but delivers much more accurate interaction - * events when enabled. - * - * @param {boolean} require Whether to require window focus. - * @return {!Options} A self reference. - */ - requireWindowFocus(require: boolean): Options; - - /** - * Configures the timeout, in milliseconds, that the driver will attempt to - * located and attach to a newly opened instance of Internet Explorer. The - * default is zero, which indicates waiting indefinitely. - * - * @param {number} timeout How long to wait for IE. - * @return {!Options} A self reference. - */ - browserAttachTimeout(timeout: number): Options; - - /** - * Configures whether to launch Internet Explorer using the CreateProcess API. - * If this option is not specified, IE is launched using IELaunchURL, if - * available. For IE 8 and above, this option requires the TabProcGrowth - * registry value to be set to 0. - * - * @param {boolean} force Whether to use the CreateProcess API. - * @return {!Options} A self reference. - */ - forceCreateProcessApi(force: boolean): Options; - - /** - * Specifies command-line switches to use when launching Internet Explorer. - * This is only valid when used with {@link #forceCreateProcessApi}. - * - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: Array): Options; - - /** - * Configures whether proxies should be configured on a per-process basis. If - * not set, setting a {@linkplain #setProxy proxy} will configure the system - * proxy. The default behavior is to use the system proxy. - * - * @param {boolean} enable Whether to enable per-process proxy settings. - * @return {!Options} A self reference. - */ - usePerProcessProxy(enable: boolean): Options; - - /** - * Configures whether to clear the cache, cookies, history, and saved form data - * before starting the browser. _Using this capability will clear session data - * for all running instances of Internet Explorer, including those started - * manually._ - * - * @param {boolean} cleanSession Whether to clear all session data on startup. - * @return {!Options} A self reference. - */ - ensureCleanSession(cleanSession: boolean): Options; - - /** - * Sets the path to the log file the driver should log to. - * @param {string} file The log file path. - * @return {!Options} A self reference. - */ - setLogFile(file: string): Options; - - /** - * Sets the IEDriverServer's logging {@linkplain Level level}. - * @param {Level} level The logging level. - * @return {!Options} A self reference. - */ - setLogLevel(level: webdriver.logging.Level): Options; - - /** - * Sets the IP address of the driver's host adapter. - * @param {string} host The IP address to use. - * @return {!Options} A self reference. - */ - setHost(host: string): Options; - - /** - * Sets the path of the temporary data directory to use. - * @param {string} path The log file path. - * @return {!Options} A self reference. - */ - setExtractPath(path: string): Options; - - /** - * Sets whether the driver should start in silent mode. - * @param {boolean} silent Whether to run in silent mode. - * @return {!Options} A self reference. - */ - silent(silent: boolean): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - -} - -declare namespace opera { - /** - * Creates {@link remote.DriverService} instances that manages an - * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) - * server in a child process. - */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the operadriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the operadriver - * cannot be found on the PATH. - */ - constructor(opt_exe?: string); - - /** - * Sets the port to start the OperaDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Sets the path of the log file the driver should log to. If a log file is - * not specified, the driver will log to stderr. - * @param {string} path Path of the log file to use. - * @return {!ServiceBuilder} A self reference. - */ - loggingTo(path: string): ServiceBuilder; - - /** - * Enables verbose logging. - * @return {!ServiceBuilder} A self reference. - */ - enableVerboseLogging(): ServiceBuilder; - - /** - * Silence sthe drivers output. - * @return {!ServiceBuilder} A self reference. - */ - silent(): ServiceBuilder; - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string|Array): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } - - /** - * Sets the default service to use for new OperaDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): any; - - /** - * Returns the default OperaDriver service. If such a service has not been - * configured, one will be constructed using the default configuration for - * a OperaDriver executable found on the system PATH. - * @return {!remote.DriverService} The default OperaDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Class for managing {@linkplain Driver OperaDriver} specific options. - */ - class Options { - /** - * Extracts the OperaDriver specific options from the given capabilities - * object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The OperaDriver options. - */ - static fromCapabilities(caps: webdriver.Capabilities): Options; - - /** - * Add additional command line arguments to use when launching the Opera - * browser. Each argument may be specified with or without the "--" prefix - * (e.g. "--foo" and "foo"). Arguments with an associated value should be - * delimited by an "=": "foo=bar". - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: Array): Options; - - /** - * Add additional extensions to install when launching Opera. Each extension - * should be specified as the path to the packed CRX file, or a Buffer for an - * extension. - * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The - * extensions to add. - * @return {!Options} A self reference. - */ - addExtensions(...var_args: Array): Options; - - /** - * Sets the path to the Opera binary to use. On Mac OS X, this path should - * reference the actual Opera executable, not just the application binary. The - * binary path be absolute or relative to the operadriver server executable, but - * it must exist on the machine that will launch Opera. - * - * @param {string} path The path to the Opera binary to use. - * @return {!Options} A self reference. - */ - setOperaBinaryPath(path: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {!./lib/logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - } - - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, - * or {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } -} - -declare namespace remote { - /** - * A record object that defines the configuration options for a DriverService - * instance. - * - * @record - */ - interface ServiceOptions {} - - /** - * Manages the life and death of a native executable WebDriver server. - * - * It is expected that the driver server implements the - * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. - * Furthermore, the managed server should support multiple concurrent sessions, - * so that this class may be reused for multiple clients. - */ - class DriverService { - /** - * @param {string} executable Path to the executable to run. - * @param {!ServiceOptions} options Configuration options for the service. - */ - constructor(executable: string, options: ServiceOptions); - - /** - * @return {!promise.Promise} A promise that resolves to - * the server's address. - * @throws {Error} If the server has not been started. - */ - address(): webdriver.promise.Promise; - - /** - * Returns whether the underlying process is still running. This does not take - * into account whether the process is in the process of shutting down. - * @return {boolean} Whether the underlying service process is running. - */ - isRunning(): boolean; - - /** - * Starts the server if it is not already running. - * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the - * server to start accepting requests. Defaults to 30 seconds. - * @return {!promise.Promise} A promise that will resolve - * to the server's base URL when it has started accepting requests. If the - * timeout expires before the server has started, the promise will be - * rejected. - */ - start(opt_timeoutMs?: number): webdriver.promise.Promise; - - /** - * Stops the service if it is not currently running. This function will kill - * the server immediately. To synchronize with the active control flow, use - * {@link #stop()}. - * @return {!promise.Promise} A promise that will be resolved when - * the server has been stopped. - */ - kill(): webdriver.promise.Promise; - - /** - * Schedules a task in the current control flow to stop the server if it is - * currently running. - * @return {!promise.Promise} A promise that will be resolved when - * the server has been stopped. - */ - stop(): webdriver.promise.Promise; - } -} - -declare namespace safari { - class Server {} - - /** - * @return {!Promise} A promise that will resolve with the path - * to Safari on the current system. - */ - function findSafariExecutable(): any; - - /** - * @param {string} serverUrl The URL to connect to. - * @return {!Promise} A promise for the path to a file that Safari can - * open on start-up to trigger a new connection to the WebSocket server. - */ - function createConnectFile(serverUrl: string): any; - - /** - * Deletes all session data files if so desired. - * @param {!Object} desiredCapabilities . - * @return {!Array} A list of promises for the deleted files. - */ - function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; - - /** @return {string} . */ - function getRandomString(): string; - - /** - * @implements {command.Executor} - */ - class CommandExecutor { - } - - /** - * Configuration options specific to the {@link Driver SafariDriver}. - */ - class Options { - /** - * Extracts the SafariDriver specific options from the given capabilities - * object. - * @param {!Capabilities} capabilities The capabilities object. - * @return {!Options} The ChromeDriver options. - */ - static fromCapabilities(capabilities: webdriver.Capabilities): Options; - - /** - * Sets whether to force Safari to start with a clean session. Enabling this - * option will cause all global browser data to be deleted. - * @param {boolean} clean Whether to make sure the session has no cookies, - * cache entries, local storage, or databases. - * @return {!Options} A self reference. - */ - setCleanSession(clean: boolean): Options; - - /** - * Sets the logging preferences for the new session. - * @param {!./lib/logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Converts this options instance to a {@link Capabilities} object. - * @param {Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * A WebDriver client for Safari. This class should never be instantiated - * directly; instead, use the {@linkplain ./builder.Builder Builder}: - * - * var driver = new Builder() - * .forBrowser('safari') - * .build(); - * - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(Options|Capabilities)=} opt_config The configuration - * options for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow to create - * the driver under. - */ - constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - - } + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; } declare namespace webdriver { namespace error { - class IError extends Error { - constructor(opt_error?: string); + interface IErrorCode { + SUCCESS: number; - code(): number; + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: number; } - /** - * The base WebDriver error type. This error type is only used directly when a - * more appropriate category is not defined for the offending error. - */ - class WebDriverError extends IError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + var ErrorCode: IErrorCode; /** - * An attempt was made to select an element that cannot be selected. + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} */ - class ElementNotSelectableError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + class Error { - /** - * An element command could not be completed because the element is not visible - * on the page. - */ - class ElementNotVisibleError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Constructors - /** - * The arguments passed to a command are either invalid or malformed. - */ - class InvalidArgumentError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); - /** - * An illegal attempt was made to set a cookie under a different domain than - * the current page. - */ - class InvalidCookieDomainError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * The coordinates provided to an interactions operation are invalid. - */ - class InvalidElementCoordinatesError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Static Properties - /** - * An element command could not be completed because the element is in an - * invalid state, e.g. attempting to click an element that is no longer attached - * to the document. - */ - class InvalidElementStateError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + }; - /** - * Argument was an invalid selector. - */ - class InvalidSelectorError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * Occurs when a command is directed to a session that does not exist. - */ - class NoSuchSessionError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Properties - /** - * An error occurred while executing JavaScript supplied by the user. - */ - class JavascriptError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; - /** - * The target for mouse interaction is not in the browser’s viewport and cannot - * be brought into that viewport. - */ - class MoveTargetOutOfBoundsError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @type {string} */ + state: string; - /** - * An attempt was made to operate on a modal dialog when one was not open. - */ - class NoSuchAlertError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @override */ + message: string; - /** - * An element could not be located on the page using the given search - * parameters. - */ - class NoSuchElementError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @override */ + name: string; - /** - * A request to switch to a frame could not be satisfied because the frame - * could not be found. - */ - class NoSuchFrameError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @override */ + stack: string; - /** - * A request to switch to a window could not be satisfied because the window - * could not be found. - */ - class NoSuchWindowError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; - /** - * A script did not complete before its timeout expired. - */ - class ScriptTimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * A new session could not be created. - */ - class SessionNotCreatedError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Methods - /** - * An element command failed because the referenced element is no longer - * attached to the DOM. - */ - class StaleElementReferenceError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @return {string} The string representation of this error. */ + toString(): string; - /** - * An operation did not completErrorCodee before its timeout expired. - */ - class TimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to set a cookie’s value could not be satisfied. - */ - class UnableToSetCookieError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A screen capture operation was not possible. - */ - class UnableToCaptureScreenError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A modal dialog was open, blocking this operation. - */ - class UnexpectedAlertOpenError extends WebDriverError { - /** - * @param {string=} opt_error the error message, if any. - * @param {string=} opt_text the text of the open dialog, if available. - */ - constructor(opt_error?: string, opt_text?: string); - - /** - * @return {(string|undefined)} The text displayed with the unhandled alert, - * if available. - */ - getAlertText(): string; - } - - /** - * A command could not be executed because the remote end is not aware of it. - */ - class UnknownCommandError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The requested command matched a known URL but did not match an method for - * that URL. - */ - class UnknownMethodError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Reports an unsupport operation. - */ - class UnsupportedOperationError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); + //endregion } } @@ -1736,97 +776,49 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string|Type, level: Level|string|number): void; + setLevel(type: string, level: ILevel): void; toJSON(): { [key: string]: string }; } + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + /** * Common log types. * @enum {string} */ - enum Type { - /** Logs originating from the browser. */ - BROWSER, - /** Logs from a WebDriver client. */ - CLIENT, - /** Logs from a WebDriver implementation. */ - DRIVER, - /** Logs related to performance. */ - PERFORMANCE, - /** Logs from the remote server. */ - SERVER - } + var Type: IType; /** - * Defines a message level that may be used to control logging output. - * - * @final + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} */ - class Level { - name_: string; - value_: number; - /** - * @param {string} name the level's name. - * @param {number} level the level's numeric value. - */ - constructor(name: string, level: number); - - /** @override */ - toString(): string; - - /** This logger's name. */ - name(): string; - - /** The numeric log level. */ - value(): number; - - /** - * Indicates no log messages should be recorded. - * @const - */ - static OFF: Level; - /** - * Log messages with a level of `1000` or higher. - * @const - */ - static SEVERE: Level; - /** - * Log messages with a level of `900` or higher. - * @const - */ - static WARNING: Level; - /** - * Log messages with a level of `800` or higher. - * @const - */ - static INFO: Level; - /** - * Log messages with a level of `700` or higher. - * @const - */ - static DEBUG: Level; - /** - * Log messages with a level of `500` or higher. - * @const - */ - static FINE: Level; - /** - * Log messages with a level of `400` or higher. - * @const - */ - static FINER: Level; - /** - * Log messages with a level of `300` or higher. - * @const - */ - static FINEST: Level; - /** - * Indicates all log messages should be recorded. - * @const - */ - static ALL: Level; + interface ILevel { + value: number; + name: string; } + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + /** * Converts a level name or value to a {@link webdriver.logging.Level} value. * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} @@ -1835,209 +827,75 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string|number): Level; + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - /** @type {!webdriver.logging.Level} */ - level: Level; + //region Constructors - /** @type {string} */ - message: string; + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); - /** @type {number} */ - timestamp: number; + //endregion - /** @type {string} */ - type: string; + //region Public Properties - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; - } + /** @type {!webdriver.logging.Level} */ + level: ILevel; - /** - * An object used to log debugging messages. Loggers use a hierarchical, - * dot-separated naming scheme. For instance, "foo" is considered the parent of - * the "foo.bar" and an ancestor of "foo.bar.baz". - * - * Each logger may be assigned a {@linkplain #setLevel log level}, which - * controls which level of messages will be reported to the - * {@linkplain #addHandler handlers} attached to this instance. If a log level - * is not explicitly set on a logger, it will inherit its parent. - * - * This class should never be directly instantiated. Instead, users should - * obtain logger references using the {@linkplain ./logging.getLogger() - * getLogger()} function. - * - * @final - */ - class Logger { - /** - * @param {string} name the name of this logger. - * @param {Level=} opt_level the initial level for this logger. - */ - constructor(name: string, opt_level?: Level); + /** @type {string} */ + message: string; - /** @private {string} */ - name_: string; - /** @private {Level} */ - level_: Level; - /** @private {Logger} */ - parent_: Logger; - /** @private {Set} */ - handlers_: any; + /** @type {number} */ + timestamp: number; - /** @return {string} the name of this logger. */ - getName(): string; + /** @type {string} */ + type: string; - /** - * @param {Level} level the new level for this logger, or `null` if the logger - * should inherit its level from its parent logger. - */ - setLevel(level: Level): void; + //endregion - /** @return {Level} the log level for this logger. */ - getLevel(): Level; + //region Static Methods - /** - * @return {!Level} the effective level for this logger. - */ - getEffectiveLevel(): Level; + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; - /** - * @param {!Level} level the level to check. - * @return {boolean} whether messages recorded at the given level are loggable - * by this instance. - */ - isLoggable(level: Level): boolean; + //endregion - /** - * Adds a handler to this logger. The handler will be invoked for each message - * logged with this instance, or any of its descendants. - * - * @param {function(!Entry)} handler the handler to add. - */ - addHandler(handler: any): void; + //region Methods - /** - * Removes a handler from this logger. - * - * @param {function(!Entry)} handler the handler to remove. - * @return {boolean} whether a handler was successfully removed. - */ - removeHandler(handler: any): void; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; - /** - * Logs a message at the given level. The message may be defined as a string - * or as a function that will return the message. If a function is provided, - * it will only be invoked if this logger's - * {@linkplain #getEffectiveLevel() effective log level} includes the given - * `level`. - * - * @param {!Level} level the level at which to log the message. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - log(level: Level, loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.SEVERE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - severe(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.WARNING} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - warning(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.INFO} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - info(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.DEBUG} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - debug(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.FINE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - fine(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.FINER} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finer(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.FINEST} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finest(loggable: string|Function): void; - } - - /** - * Maintains a collection of loggers. - * - * @final - */ - class LogManager { - /** - * Retrieves a named logger, creating it in the process. This function will - * implicitly create the requested logger, and any of its parents, if they - * do not yet exist. - * - * @param {string} name the logger's name. - * @return {!Logger} the requested logger. - */ - getLogger(name: string): Logger; - - /** - * Creates a new logger. - * - * @param {string} name the logger's name. - * @param {!Logger} parent the logger's parent. - * @return {!Logger} the new logger. - * @private - */ - createLogger_(name: string, parent: Logger): Logger; + //endregion } } @@ -2050,15 +908,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array<(T|!ManagedPromise)>} arr An array of + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of * promises to wait on. - * @return {!ManagedPromise>} A promise that is + * @return {!webdriver.promise.Promise.>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Array>): Promise; + function all(arr: Promise[]): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -2081,9 +939,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!ControlFlow)} callback The entry point + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point * to the newly created flow. - * @return {!ManagedPromise} A promise that resolves to the callback + * @return {!webdriver.promise.Promise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -2108,7 +966,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!ManagedPromise} The promise. + * @return {!webdriver.promise.Promise} The promise. */ function delayed(ms: number): Promise; @@ -2116,25 +974,26 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - * If the return value of the filter function is a promise, this function + *

If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - * If the filter function throws or returns a rejected promise, the promise + *

If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array|ManagedPromise>)} arr The + * @param {!(Array.|webdriver.promise.Promise.>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ( - * boolean|ManagedPromise)} fn The function + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise /** * Creates a new deferred object. @@ -2144,9 +1003,8 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {T=} opt_value The resolved value. - * @return {!ManagedPromise} The resolved promise. - * @template T + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. */ function fulfilled(opt_value?: T): Promise; @@ -2155,44 +1013,42 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - * If the return value of the mapping function is a promise, this function + *

If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - * If the mapping function throws or returns a rejected promise, the + *

If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array|ManagedPromise>)} arr The + * @param {!(Array.|webdriver.promise.Promise.>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!ManagedPromise} The rejected promise. - * @template T + * @return {!webdriver.promise.Promise} The rejected promise. */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that expects a node-style callback as its final - * argument. This callback expects two arguments: an error value (which will be + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * The callback will the resolve or reject the returned promise, based on its - * arguments. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. * @param {!Function} fn The function to wrap. - * @param {...?} var_args The arguments to apply to the function, excluding the - * final callback. - * @return {!ManagedPromise} A promise that will be resolved with the + * @return {!webdriver.promise.Promise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -2203,35 +1059,37 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - * __Example 1:__ the Fibonacci Sequence. + *

Example 1: the Fibonacci Sequence. + *


+         * webdriver.promise.consume(function* fibonacci() {
+         *   var n1 = 1, n2 = 1;
+         *   for (var i = 0; i < 4; ++i) {
+         *     var tmp = yield n1 + n2;
+         *     n1 = n2;
+         *     n2 = tmp;
+         *   }
+         *   return n1 + n2;
+         * }).then(function(result) {
+         *   console.log(result);  // 13
+         * });
+         * 
* - * promise.consume(function* fibonacci() { - * var n1 = 1, n2 = 1; - * for (var i = 0; i < 4; ++i) { - * var tmp = yield n1 + n2; - * n1 = n2; - * n2 = tmp; - * } - * return n1 + n2; - * }).then(function(result) { - * console.log(result); // 13 - * }); - * - * __Example 2:__ a generator that throws. - * - * promise.consume(function* () { - * yield promise.delayed(250).then(function() { - * throw Error('boom'); - * }); - * }).catch(function(e) { - * console.log(e.toString()); // Error: boom - * }); + *

Example 2: a generator that throws. + *


+         * webdriver.promise.consume(function* () {
+         *   yield webdriver.promise.delayed(250).then(function() {
+         *     throw Error('boom');
+         *   });
+         * }).thenCatch(function(e) {
+         *   console.log(e.toString());  // Error: boom
+         * });
+         * 
* * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!ManagedPromise} A promise that will resolve to the + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -2246,9 +1104,10 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!ManagedPromise} A new promise. + * @return {!webdriver.promise.Promise} A new promise. */ - function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -2261,19 +1120,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!ManagedPromise} A promise for a fully resolved version + * @return {!webdriver.promise.Promise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!ControlFlow} flow The new default flow. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -2282,249 +1141,63 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final */ - class CancellationError extends Error { - /** - * @param {string=} opt_msg The cancellation message. - */ - constructor(opt_msg?: string); + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: string; } interface IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string|Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - } - - /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ - class Thenable implements IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string|Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } finally { - * cleanUp(); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().finally(cleanUp); - * - * __Note:__ similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - * - * try { - * throw Error('one'); - * } finally { - * throw Error('two'); // Hides Error: one - * } - * - * promise.rejected(Error('one')) - * .finally(function() { - * throw Error('two'); // Hides Error: one - * }); - * - * @param {function(): (R|IThenable)} callback The function to call when - * this promise is resolved. - * @return {!ManagedPromise} A promise that will be fulfilled - * with the callback result. - * @template R - */ - finally(callback: Function): Promise; - - /** - * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function - * will also ensure the prototype's {@code then} function is exported from - * compiled code. - * @param {function(new: Thenable, ...?)} ctor The - * constructor whose prototype to modify. - */ - static addImplementation(ctor: Function): void; - - /** - * Checks if an object has been tagged for implementing the Thenable - * interface as defined by {@link Thenable.addImplementation}. - * @param {*} object The object to test. - * @return {boolean} Whether the object is an implementation of the Thenable - * interface. - */ - static isImplementation(object: any): boolean; - } - - interface IFulfilledCallback { - (value: T|IThenable|Thenable|void): void; - } - - interface IRejectedCallback { - (reason: any): void; - } - - /** - * Represents the eventual value of a completed operation. Each promise may be - * in one of three states: pending, fulfilled, or rejected. Each promise starts - * in the pending state and may make a single transition to either a - * fulfilled or rejected state, at which point the promise is considered - * resolved. - * - * @implements {promise.Thenable} - * @template T - * @see http://promises-aplus.github.io/promises-spec/ - */ - class Promise implements IThenable { - /** - * @param {function( - * function((T|IThenable|Thenable)=), - * function(*=))} resolver - * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback - * functions, one for fulfilling the promise and another for rejecting it. - * @param {ControlFlow=} opt_flow The control flow - * this instance was created under. Defaults to the currently active flow. - */ - constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); - constructor(); // For angular-protractor/angular-protractor-tests.ts - - //region Methods - /** * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. */ - cancel(opt_reason?: string|Error): void; + cancel(opt_reason?: string): void; + /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; + /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. + * Registers listeners for when this instance is resolved. * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. */ - then(opt_callback?: Function, opt_errback?: Function): Promise; + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2552,31 +1225,6 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - /** * Registers a listener to invoke when this promise is resolved, regardless @@ -2617,7 +1265,294 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: Function): Promise; + thenFinally(callback: () => any): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function will + * also ensure the prototype's {@code then} function is exported from compiled + * code. + * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + + /** + * Checks if an object has been tagged for implementing the Thenable interface + * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T|IThenable|Thenable|void): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback functions, + * one for fulfilling the promise and another for rejecting it. + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor + */ + constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); + constructor(); // For angular-protractor/angular-protractor-tests.ts + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(reason: any): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } catch (ex) {
+             *     console.error(ex);
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenCatch(function(ex) {
+             *     console.error(ex);
+             *   });
+             * 
+ * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *

+             *   // Synchronous API:
+             *   try {
+             *     doSynchronousWork();
+             *   } finally {
+             *     cleanUp();
+             *   }
+             *
+             *   // Asynchronous promise API:
+             *   doAsynchronousWork().thenFinally(cleanUp);
+             * 
+ * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *

+             *   try {
+             *     throw Error('one');
+             *   } finally {
+             *     throw Error('two');  // Hides Error: one
+             *   }
+             *
+             *   webdriver.promise.rejected(Error('one'))
+             *       .thenFinally(function() {
+             *         throw Error('two');  // Hides Error: one
+             *       });
+             * 
+ * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; //endregion } @@ -2856,6 +1791,107 @@ declare namespace webdriver { } } + namespace stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + namespace until { /** * Defines a condition to @@ -2879,31 +1915,32 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as + * to the designated frame. The target frame may be specified as: + *
    + *
  1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
  2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
  3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
* - * 1. a numeric index into - * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) - * for the currently selected frame. - * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - * 3. a locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - * - * Upon successful resolution of this condition, the driver will be left + *

Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|./webdriver.WebElement|By| - * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame * The frame identifier. - * @return {!Condition} A new condition. + * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function alertIsPresent(): Condition; @@ -2963,12 +2000,13 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link ./webdriver.WebDriver#findElement found} with the given locator. + * {@link webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(By|Function)} locator The locator to use. + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: By|Function): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -3001,7 +2039,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -3015,7 +2053,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: By|Function): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -3023,7 +2061,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -3042,7 +2080,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function titleIs(title: string): Condition; @@ -3067,18 +2105,18 @@ declare namespace webdriver { } /** - * Representations of pressable keys that aren't text. These are stored in - * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to - * http://www.google.com.au/search?&q=unicode+pua&btnG=Search - * - * @enum {string} + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} */ - enum Button { - LEFT, - MIDDLE, - RIGHT, + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; } + var Button: IButton; + /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -3086,86 +2124,102 @@ declare namespace webdriver { * * @enum {string} */ - enum Key { - NULL, - CANCEL, // ^break - HELP, - BACK_SPACE, - TAB, - CLEAR, - RETURN, - ENTER, - SHIFT, - CONTROL, - ALT, - PAUSE, - ESCAPE, - SPACE, - PAGE_UP, - PAGE_DOWN, - END, - HOME, - ARROW_LEFT, - LEFT, - ARROW_UP, - UP, - ARROW_RIGHT, - RIGHT, - ARROW_DOWN, - DOWN, - INSERT, - DELETE, - SEMICOLON, - EQUALS, + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; - NUMPAD0, // number pad keys - NUMPAD1, - NUMPAD2, - NUMPAD3, - NUMPAD4, - NUMPAD5, - NUMPAD6, - NUMPAD7, - NUMPAD8, - NUMPAD9, - MULTIPLY, - ADD, - SEPARATOR, - SUBTRACT, - DECIMAL, - DIVIDE, + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; - F1, // function keys - F2, - F3, - F4, - F5, - F6, - F7, - F8, - F9, - F10, - F11, - F12, + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; - COMMAND, // Apple command key - META // alias for Windows key + COMMAND: string; // Apple command key + META: string; // alias for Windows key + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; } + var Key: IKey; + /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - * Example: - * - * new ActionSequence(driver). - * keyDown(Key.SHIFT). - * click(element1). - * click(element2). - * dragAndDrop(element3, element4). - * keyUp(Key.SHIFT). - * perform(); + *

Example:


+     *   new webdriver.ActionSequence(driver).
+     *       keyDown(webdriver.Key.SHIFT).
+     *       click(element1).
+     *       click(element2).
+     *       dragAndDrop(element3, element4).
+     *       keyUp(webdriver.Key.SHIFT).
+     *       perform();
+     * 
* */ class ActionSequence { @@ -3193,18 +2247,14 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in - * pixels. - * @param {{x: number, y: number}=} opt_offset If the target {@code location} - * is defined as a {@link ./webdriver.WebElement}, this parameter defines - * an offset within that element. The offset should be specified in pixels - * relative to the top-left corner of the element's bounding box. If - * omitted, the element's center will be used as the target offset. - * @return {!ActionSequence} A self reference. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in pixels. + * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. */ - mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -3212,101 +2262,100 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - * If an element is provided, the mouse will first be moved to the center + *

If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseDown()
* - * sequence.mouseMove(element).mouseDown() + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - * If an element is provided, the mouse will first be moved to the center + *

If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: + *

sequence.mouseMove(element).mouseUp()
* - * sequence.mouseMove(element).mouseUp() + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * - * @param {!./webdriver.WebElement} element The element to drag. - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in - * pixels. - * @return {!ActionSequence} A self reference. + * @param {!webdriver.WebElement} element The element to drag. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in pixels. + * @return {!webdriver.ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: ILocation): ActionSequence; /** * Clicks a mouse button. * - * If an element is provided, the mouse will first be moved to the center + *

If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: + *

sequence.mouseMove(element).click()
* - * sequence.mouseMove(element).click() - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; /** * Double-clicks a mouse button. * - * If an element is provided, the mouse will first be moved to the center of + *

If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: + *

sequence.mouseMove(element).doubleClick()
* - * sequence.mouseMove(element).doubleClick() + *

Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -3317,7 +2366,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: Key): ActionSequence; + keyDown(key: string): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -3327,7 +2376,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: Key): ActionSequence; + keyUp(key: string): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -3338,7 +2387,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: Array): ActionSequence; + sendKeys(...var_args: any[]): ActionSequence; //endregion } @@ -3434,6 +2483,7 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; + /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -3444,6 +2494,7 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -3453,6 +2504,7 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; + /** * Flick starting at elem and moving by x and y at specified speed. * @@ -3464,29 +2516,26 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } + interface IOffset { x: number; y: number; } + interface ISpeed { xspeed: number; yspeed: number; } + /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - class Alert { - /** - * @param {!WebDriver} driver The driver controlling the browser this alert - * is attached to. - * @param {string} text The message text displayed with this alert. - */ - constructor(driver: WebDriver, text: string); + interface Alert { //region Methods @@ -3498,18 +2547,6 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; - /** - * Sets the username and password in an alert prompting for credentials (such - * as a Basic HTTP Auth prompt). This method will implicitly - * {@linkplain #accept() submit} the dialog. - * - * @param {string} username The username to send. - * @param {string} password The password to send. - * @return {!promise.Promise} A promise that will be resolved when this - * command has completed. - */ - authenticateAs(username: string, password: string): webdriver.promise.Promise; - /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -3543,27 +2580,47 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - * + *


      *     driver.switchTo().alert().dismiss();
      *     driver.switchTo().alert().then(function(alert) {
      *       return alert.dismiss();
      *     });
+     * 
* - * @implements {promise.Thenable.} + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.promise.Thenable.} * @final */ - class AlertPromise extends Alert { - /** - * @param {!WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!promise.Thenable} alert A thenable - * that will be fulfilled with the promised alert. - */ - constructor(driver: WebDriver, alert: webdriver.promise.Promise); + interface AlertPromise extends Alert, webdriver.promise.IThenable { } - /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ - class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion } /** @@ -3573,9 +2630,7 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; - EDGE: string; FIREFOX: string; - IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -3596,45 +2651,6 @@ declare namespace webdriver { noProxy?: string; } - /** - * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment - * variables listed below may be used to override a builder's configuration, - * allowing quick runtime changes. - * - * - {@code SELENIUM_BROWSER}: defines the target browser in the form - * {@code browser[:version][:platform]}. - * - * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder - * instances. This environment variable should be set to a fully qualified - * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This - * option always takes precedence over {@code SELENIUM_SERVER_JAR}. - * - * - {@code SELENIUM_SERVER_JAR}: defines the path to the - * - * standalone Selenium server jar to use. The server will be started the - * first time a WebDriver instance and be killed when the process exits. - * - * Suppose you had mytest.js that created WebDriver with - * - * var driver = new webdriver.Builder() - * .forBrowser('chrome') - * .build(); - * - * This test could be made to use Firefox on the local machine by running with - * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to - * target Google Chrome on a remote machine, you can simply set the - * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: - * - * SELENIUM_BROWSER=chrome:36:LINUX \ - * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ - * node mytest.js - * - * You could also use a local copy of the standalone Selenium server: - * - * SELENIUM_BROWSER=chrome:36:LINUX \ - * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ - * node mytest.js - */ class Builder { //region Constructors @@ -3648,45 +2664,15 @@ declare namespace webdriver { //region Methods - /** - * Configures this builder to ignore any environment variable overrides and to - * only use the configuration specified through this instance's API. - * - * @return {!Builder} A self reference. - */ - disableEnvironmentOverrides(): Builder; - /** * Creates a new WebDriver client based on this builder's current * configuration. * - * While this method will immediately return a new WebDriver instance, any - * commands issued against it will be deferred until the associated browser - * has been fully initialized. Users may call {@link #buildAsync()} to obtain - * a promise that will not be fulfilled until the browser has been created - * (the difference is purely in style). - * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. - * @see #buildAsync() */ build(): WebDriver; - /** - * Creates a new WebDriver client based on this builder's current - * configuration. This method returns a promise that will not be fulfilled - * until the new browser session has been fully initialized. - * - * __Note:__ this method is purely a convenience wrapper around - * {@link #build()}. - * - * @return {!promise.Promise} A promise that will be - * fulfilled with the newly created WebDriver instance once the browser - * has been fully initialized. - * @see #build() - */ - buildAsync(): webdriver.promise.Promise; - /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -3719,12 +2705,6 @@ declare namespace webdriver { */ getServerUrl(): string; - /** - * @return {?string} The URL of the proxy server to use for the WebDriver's - * HTTP connections, or `null` if not set. - */ - getWebDriverProxy(): string; - /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -3755,17 +2735,6 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; - /** - * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser - * for drivers created by this builder. Any proxy settings defined on the - * given options will take precedence over those set through - * {@link #setProxy}. - * - * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. - * @return {!Builder} A self reference. - */ - setEdgeOptions(options: edge.Options): Builder; - /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -3784,16 +2753,6 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; - /** - * Set Internet Explorer specific {@linkplain ie.Options options} for drivers - * created by this builder. Any proxy settings defined on the given options - * will take precedence over those set through {@link #setProxy}. - * - * @param {!ie.Options} options The IEDriver options to use. - * @return {!Builder} A self reference. - */ - setIeOptions(options: ie.Options): Builder; - /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -3801,37 +2760,17 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; - - /** - * Sets Opera specific {@linkplain opera.Options options} for drivers created - * by this builder. Any logging or proxy settings defined on the given options - * will take precedence over those set through {@link #setLoggingPrefs} and - * {@link #setProxy}, respectively. - * - * @param {!opera.Options} options The OperaDriver options to use. - * @return {!Builder} A self reference. - */ - setOperaOptions(options: opera.Options): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!capabilities.ProxyConfig} config The configuration to use. + * @param {!webdriver.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: webdriver.ProxyConfig): Builder; - - /** - * Sets Safari specific {@linkplain safari.Options options} for drivers - * created by this builder. Any logging settings defined on the given options - * will take precedence over those set through {@link #setLoggingPrefs}. - * - * @param {!safari.Options} options The Safari options to use. - * @return {!Builder} A self reference. - */ - setSafari(options: safari.Options): Builder; + setProxy(config: ProxyConfig): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -3854,16 +2793,6 @@ declare namespace webdriver { */ usingServer(url: string): Builder; - /** - * Sets the URL of the proxy to use for the WebDriver's HTTP connections. - * If this method is never called, the Builder will create a connection - * without a proxy. - * - * @param {string} proxy The URL of a proxy to use. - * @return {!Builder} A self reference. - */ - usingWebDriverProxy(proxy: string): Builder; - /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -3871,149 +2800,12 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Object|Capabilities): Builder; + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; //endregion } - /** - * Describes a mechanism for locating an element on the page. - * @final - */ - class By { - - /** - * @param {string} using the name of the location strategy to use. - * @param {string} value the value to search for. - */ - constructor(using: string, value: string); - - /** - * Locates elements that have a specific class name. - * - * @param {string} name The class name to search for. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - static className(name: string): By; - - /** - * Locates elements using a CSS selector. - * - * @param {string} selector The CSS selector to use. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - static css(selector: string): By; - - /** - * Locates eleemnts by the ID attribute. This locator uses the CSS selector - * `*[id="$ID"]`, _not_ `document.getElementById`. - * - * @param {string} id The ID to search for. - * @return {!By} The new locator. - */ - static id(id: string): By; - - /** - * Locates link elements whose - * {@linkplain webdriver.WebElement#getText visible text} matches the given - * string. - * - * @param {string} text The link text to search for. - * @return {!By} The new locator. - */ - static linkText(text: string): By; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!./webdriver.WebDriver): !./promise.Promise} - * A new JavaScript-based locator function. - */ - static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose `name` attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!By} The new locator. - */ - static name(name: string): By; - - /** - * Locates link elements whose - * {@linkplain webdriver.WebElement#getText visible text} contains the given - * substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!By} The new locator. - */ - static partialLinkText(text: string): By; - - /** - * Locates elements with a given tag name. - * - * @param {string} name The tag name to search for. - * @return {!By} The new locator. - * @deprecated Use {@link By.css() By.css(tagName)} instead. - */ - static tagName(name: string): By; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector `//div`, WebDriver will search from the document root - * regardless of whether the locator was used with a WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - static xpath(xpath: string): By; - - /** @override */ - toString(): string; - } - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type ByHash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - /** * Common webdriver capability keys. * @enum {string} @@ -4084,7 +2876,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -4118,7 +2910,8 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities|Object); + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); //endregion @@ -4134,7 +2927,8 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities|Object): Capabilities; + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; /** * @param {string} key The capability to set. @@ -4152,7 +2946,9 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + /** * Sets the proxy configuration for this instance. @@ -4214,11 +3010,6 @@ declare namespace webdriver { */ static chrome(): Capabilities; - /** - * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. - */ - static edge(): Capabilities; - /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -4392,8 +3183,6 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; - - UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -4452,47 +3241,19 @@ declare namespace webdriver { } /** - * Handles the execution of WebDriver {@link Command commands}. - * @interface + * Handles the execution of {@code webdriver.Command} objects. */ - class Executor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * response object. - * - * @param {!Command} command The command to execute. - * @return {!promise.Promise} A promise that will be fulfilled with - * the command result. - */ - execute(command: Command): webdriver.promise.Promise - } - - /** - * Wraps a promised {@link Executor}, ensuring no commands are executed until - * the wrapped executor has been fully resolved. - * @implements {Executor} - */ - class DeferredExecutor { - /** - * @param {!promise.Promise} delegate The promised delegate, which - * may be provided by any promise-like thenable object. - */ - constructor(delegate: webdriver.promise.Promise); - } - - /** - * Describes an event listener registered on an {@linkplain EventEmitter}. - */ - class Listener { - /** - * @param {!Function} fn The acutal listener function. - * @param {(Object|undefined)} scope The object in whose scope to invoke the - * listener. - * @param {boolean} oneshot Whether this listener should only be used once. - */ - constructor(fn: Function, scope: Object, oneshot: boolean); + interface CommandExecutor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; } /** @@ -4522,42 +3283,39 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Set} The registered listeners for the given event - * type. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. */ - listeners(type: string): any; + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. - * @param {Object=} opt_self The object in whose scope to invoke the listener. - * @param {boolean=} opt_oneshot Whether the listener should b (e removed after - * the first event is fired. - * @return {!EventEmitter} A self reference. - * @private + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. */ - addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; - + addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. + * @param {!Function} listenerFn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, fn: any, opt_scope?: any): EventEmitter; + once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. + * @param {!Function} listenerFn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, fn: Function, opt_scope?:any): EventEmitter; + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -4582,20 +3340,14 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - class Navigation { + interface WebDriverNavigation { //region Constructors /** - * Interface for navigating back and forth in the browser history. - * - * This class should never be instantiated directly. Insead, obtain an instance - * with - * - * webdriver.navigate() - * - * @see WebDriver#navigate() + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor */ - constructor(driver: WebDriver); + new (driver: WebDriver): WebDriverNavigation; //endregion @@ -4645,14 +3397,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - class Options { + interface WebDriverOptions { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: webdriver.WebDriver): WebDriverOptions; //endregion @@ -4665,13 +3417,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified - * as a number, should be in milliseconds since midnight, - * January 1, 1970 UTC. - * @return {!promise.Promise} A promise that will be resolved - * when the cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as + * a number, should be in milliseconds since midnight, January 1, 1970 UTC. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -4715,19 +3467,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): webdriver.Logs; + logs(): WebDriverLogs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): webdriver.Timeouts; + timeouts(): WebDriverTimeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): webdriver.Window; + window(): WebDriverWindow; //endregion } @@ -4735,14 +3487,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - class Timeouts { + interface WebDriverTimeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTimeouts; //endregion @@ -4797,7 +3549,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - class Window { + interface WebDriverWindow { //region Constructors @@ -4805,7 +3557,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverWindow; //endregion @@ -4860,7 +3612,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - class Logs { + interface WebDriverLogs { //region Constructors @@ -4868,7 +3620,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverLogs; //endregion @@ -4888,7 +3640,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: webdriver.logging.Type): webdriver.promise.Promise; + get(type: string): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -4903,7 +3655,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - class TargetLocator { + interface WebDriverTargetLocator { //region Constructors @@ -4911,7 +3663,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTargetLocator; //endregion @@ -4935,47 +3687,44 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. The target frame may be specified as one of the - * following: - * - * - A number that specifies a (zero-based) index into [window.frames]( - * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). - * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` - * DOM element. - * - The `null` value, to select the topmost frame on the page. Passing `null` - * is the same as calling {@link #defaultContent defaultContent()}. - * - * If the specified frame can not be found, the returned promise will be - * rejected with a {@linkplain error.NoSuchFrameError}. - * - * @param {(number|WebElement|null)} id The frame locator. - * @return {!promise.Promise} A promise that will be resolved - * when the driver has changed focus to the specified frame. + * frame on the page. + *

+ * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

+ * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

+ * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. */ - frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@link WebDriver#getWindowHandles}). - * - * If the specified window cannot be found, the returned promise will be - * rejected with a {@linkplain error.NoSuchWindowError}. - * + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

+ * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!promise.Promise} A promise that will be resolved - * when the driver has changed focus to the specified window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active modal dialog, such as - * those opened by `window.alert()`, `window.confirm()`, and - * `window.prompt()`. The returned promise will be rejected with a - * {@linkplain error.NoSuchAlertError} if there are no open alerts. - * - * @return {!AlertPromise} The open alert. + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. */ alert(): AlertPromise; @@ -5040,14 +3789,27 @@ declare namespace webdriver { //region Constructors /** - * @param {!(Session|promise.Promise)} session Either a + * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!command.Executor} executor The executor to use when sending - * commands to the browser. - * @param {promise.ControlFlow=} opt_flow The flow to + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. + * @constructor */ - constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; //endregion @@ -5055,29 +3817,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!command.Executor} executor Command executor to use when querying - * for session details. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. * @param {string} sessionId ID of the session to attach to. - * @param {promise.ControlFlow=} opt_flow The control flow all - * driver commands should execute under. Defaults to the - * {@link promise.controlFlow() currently active} control flow. - * @return {!WebDriver} A new client for the specified session. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. */ - static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!command.Executor} executor The executor to create the new session - * with. - * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow all driver + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link promise.controlFlow() currently active} + * Defaults to the {@link webdriver.promise.controlFlow() currently active} * control flow. - * @return {!WebDriver} The driver for the newly created session. + * @return {!webdriver.WebDriver} The driver for the newly created session. */ - static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -5090,22 +3852,20 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@link command.Command} to be executed by this driver's - * {@link command.Executor}. - * - * @param {!command.Command} command The command to schedule. + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!promise.Promise} A promise that will be resolved - * with the command result. - * @template T + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain input.FileDetector file detector} that should be + * Sets the {@linkplain webdriver.FileDetector file detector} that should be * used with this instance. - * @param {input.FileDetector} detector The detector to use or {@code null}. + * @param {webdriver.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -5135,23 +3895,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.ActionSequence#perform} is + * scheduled for execution until {@link webdriver.ActionSequence#perform} is * called. Example: - * - * driver.actions(). - * mouseDown(element1). - * mouseMove(element2). - * mouseUp(). - * perform(); - * - * @return {!actions.ActionSequence} A new action sequence for this instance. + *


+         *   driver.actions().
+         *       mouseDown(element1).
+         *       mouseMove(element2).
+         *       mouseUp().
+         *       perform();
+         * 
+ * @return {!webdriver.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.TouchSequence#perform} is + * scheduled for execution until {@link webdriver.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -5159,7 +3919,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!actions.TouchSequence} A new touch sequence for this instance. + * @return {!webdriver.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -5201,7 +3961,8 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -5418,27 +4179,38 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input this - * instance and returns a {@link WebElement}, or a promise that will resolve - * to a WebElement. If the returned promise resolves to an array of - * WebElements, WebDriver will use the first element. For example, to find the - * first visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return promise.filter(links, function(link) { - * return link.isDisplayed(); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; * }); * } * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!WebElementPromise} A WebElement that can be used to issue + * When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The + * locator to use. + * @return {!webdriver.WebElement} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By|Function): WebElementPromise; + findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -5447,36 +4219,35 @@ declare namespace webdriver { * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise} A promise that will resolve + * @param {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual + * DOM element to be located by the server. + * @return {!webdriver.promise.Promise.} A promise that will resolve * with whether the element is present on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise.>} A + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: + *
    + *
  1. Entire page + *
  2. Current window + *
  3. Visible portion of the current frame + *
  4. The screenshot of the entire display containing the browser + *
* - * 1. Entire page - * 2. Current window - * 3. Visible portion of the current frame - * 4. The entire display containing the browser - * - * @return {!promise.Promise} A promise that will be + * @return {!webdriver.promise.Promise.} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -5485,25 +4256,45 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): webdriver.Options; + manage(): WebDriverOptions; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): Navigation; + navigate(): WebDriverNavigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): webdriver.TargetLocator; + switchTo(): WebDriverTargetLocator; //endregion } interface IWebElementId { - [ELEMENT:string]: string; + ELEMENT: string; + } + + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; } /** @@ -5763,7 +4554,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By|Function): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -5774,7 +4565,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: By|Function): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -5785,9 +4576,10 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } + /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -5808,6 +4600,7 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } + /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -5833,59 +4626,35 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!WebDriver} driver the parent WebDriver instance for this element. - * @param {(!IThenable|string)} id The server-assigned opaque ID for - * the underlying DOM element. + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor */ - constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); /** - * @param {string} id The raw ID. - * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. - * @return {!Object} The element ID for use with WebDriver's wire protocol. + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol */ - static buildId(id: string, opt_noLegacy?: boolean): Object; + static Id: IWebElementId; /** - * Extracts the encoded WebElement ID from the object. - * - * @param {?} obj The object to extract the ID from. - * @return {string} the extracted ID. - * @throws {TypeError} if the object is not a valid encoded ID. + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const */ - static extractId(obj: IWebElementId): string; + static ELEMENT_KEY: string; - /** - * @param {?} obj the object to test. - * @return {boolean} whether the object is a valid encoded WebElement ID. - */ - static isId(obj: IWebElementId): boolean; - - /** - * Compares two WebElements for equality. - * - * @param {!WebElement} a A WebElement. - * @param {!WebElement} b A WebElement. - * @return {!promise.Promise} A promise that will be - * resolved to whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): webdriver.WebDriver; - - /** - * @return {!promise.Promise} A promise that resolves to - * the server-assigned opaque ID assigned to this element. - */ - getId(): webdriver.promise.Promise; - - /** - * @deprecated Use {@link #getId()} instead. - */ - getRawId(): any; + getDriver(): WebDriver; /** * Schedule a command to find a descendant of this element. If the element @@ -5919,40 +4688,35 @@ declare namespace webdriver { * }); * } * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!WebElementPromise} A WebElement that can be used to issue + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By|Function): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise} A promise that will be + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: By|Function): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise>} A + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -5963,7 +4727,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * promsieinstance. + * instance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -6035,7 +4799,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!promise.Promise} A promise that will be + * @return {!webdriver.promise.Promise.} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -6121,10 +4885,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the `value` of this element. This command has - * no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!promise.Promise} A promise that will be resolved + * @return {!webdriver.promise.Promise.} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -6136,18 +4900,6 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; - /** - * Take a screenshot of the visible region encompassed by this element's - * bounding rectangle. - * - * @param {boolean=} opt_scroll Optional argument that indicates whether the - * element should be scrolled into view before taking a screenshot. - * Defaults to false. - * @return {!promise.Promise} A promise that will be - * resolved to the screenshot as a base-64 encoded PNG. - */ - takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; - /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -6155,6 +4907,25 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -6162,8 +4933,14 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** @override */ - serialize(): webdriver.promise.Promise; + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; } /** @@ -6189,14 +4966,6 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { - /** - * @param {!WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!promise.Promise} el A promise - * that will resolve to the promised element. - */ - constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); - /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -6306,31 +5075,191 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; + } + + namespace By { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + function className(value: string): Locator; /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector API. * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html */ - catch(errback: Function): webdriver.promise.Promise; + function css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ + function id(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ + function linkText(value: string): Locator; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ + function name(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} contains the given substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + */ + function partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ + function tagName(value: string): Locator; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector {@code "//div"}, WebDriver will search from the + * document root regardless of whether the locator was used with a + * WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + function xpath(value: string): Locator; + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + /** + * An element locator. + */ + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); + + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + /** @return {string} String representation of this locator. */ + toString(): string; } /** @@ -6346,7 +5275,8 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities|Object); + constructor(id: string, capabilities: Capabilities); + constructor(id: string, capabilities: any); //endregion @@ -6360,7 +5290,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): webdriver.Capabilities; + getCapabilities(): Capabilities; /** * Retrieves the value of a specific capability. @@ -6446,6 +5376,10 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + declare module 'selenium-webdriver/executors' { export = executors; } From 08850929a37774c447dba246e80a2e65d5035d33 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 17:10:58 +0800 Subject: [PATCH 030/154] Since express has been imported, it should be used --- twilio/twilio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8ef14760b8..d6c2dfebf7 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -449,7 +449,7 @@ declare module twilio { export function webhook(options?: string | webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; - export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; + export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; /// resources/Accounts.js export interface OutgoingCallerIdInstance extends InstanceResource { From a715a568847661320c4f643dc1c6f318c0a3e440 Mon Sep 17 00:00:00 2001 From: Jonny Stoten Date: Thu, 15 Sep 2016 14:19:23 +0100 Subject: [PATCH 031/154] Add some typings for multipart upload (#11223) --- aws-sdk/aws-sdk.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index b950790058..09ec2f6267 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -236,6 +236,11 @@ declare module "aws-sdk" { listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void; listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void; waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + + createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; + uploadPart(params: any, callback: (err: Error, data: any) => void): void; + listParts(params: any, callback: (err: Error, data: any) => void): void; + completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; } export class STS { From 1a97636e037e5a0c1dff8d723c8585db24ccf433 Mon Sep 17 00:00:00 2001 From: paulmorphy Date: Thu, 15 Sep 2016 15:20:21 +0200 Subject: [PATCH 032/154] Added definition for the missing dns.setServers(servers) method (#11183) * Added definition for the missing dns.setServers(servers) method Method is documented here: https://nodejs.org/docs/latest/api/dns.html#dns_dns_setservers_servers * Updated definition for dns.resolveMx The addresses argument passed to the callback function will contain an array of objects containing both a priority and exchange property: https://nodejs.org/docs/latest/api/dns.html#dns_dns_resolvemx_hostname_callback --- node/node.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index 2094959e6e..e4e66e69ee 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1396,18 +1396,24 @@ declare module "url" { } declare module "dns" { + export interface MxRecord { + exchange: string, + priority: number + } + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) =>void ): string[]; export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; + export function setServers(servers: string[]): void; //Error codes export var NODATA: string; From 6a9eb69291eb1154cce41664c668ab479c6c5732 Mon Sep 17 00:00:00 2001 From: Kazuki Oota Date: Thu, 15 Sep 2016 22:22:12 +0900 Subject: [PATCH 033/154] add access property to table. (#11158) * add access property. * fix ci error. --- azure-mobile-apps/azure-mobile-apps-tests.ts | 7 +++++++ azure-mobile-apps/azure-mobile-apps.d.ts | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 6b994b4f05..302f732889 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.access = undefined; +table.access = 'authenticated'; +table.read.access = 'anonymous'; +table.update.access = 'disabled'; +table.delete.access = 'authenticated'; +table.insert.access = 'authenticated'; + // Express.Table, instantiated from the static require('azure-mobile-apps').table() // This is going to be interesting if we ever support more than one provider var table2 = mobileApps.table(); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 436d88b3cb..a17e41e2d6 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -47,6 +47,7 @@ declare namespace Azure.MobileApps { interface Table { authorize?: boolean; + access?: AccessType; autoIncrement?: boolean; dynamicSchema?: boolean; name: string; @@ -66,8 +67,11 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; + access: AccessType; } + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; From d51cb64351dad6f50a890d8cd2ddb2c2a90e3104 Mon Sep 17 00:00:00 2001 From: Jacob Baskin Date: Thu, 15 Sep 2016 09:24:40 -0400 Subject: [PATCH 034/154] Typings for Busboy (#11227) * Add typings for Busboy. * Fix indent style * Fix for es6 imports * Re-add module def --- busboy/busboy-tests.ts | 39 +++++++++++++++++++++++++++ busboy/busboy.d.ts | 60 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 busboy/busboy-tests.ts create mode 100644 busboy/busboy.d.ts diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts new file mode 100644 index 0000000000..058b5c92d3 --- /dev/null +++ b/busboy/busboy-tests.ts @@ -0,0 +1,39 @@ +/// +/// + +import * as Busboy from 'busboy'; +import * as http from 'http'; +import * as util from 'util'; + +function serverFn(req: http.ServerRequest, res: http.ServerResponse) { + if (req.method === 'POST') { + var busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); + file.on('data', function(data: Buffer) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) { + console.log('Field [' + fieldname + ']: value: ' + util.inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + \ +
\ + '); + } +} diff --git a/busboy/busboy.d.ts b/busboy/busboy.d.ts new file mode 100644 index 0000000000..3b64f3d112 --- /dev/null +++ b/busboy/busboy.d.ts @@ -0,0 +1,60 @@ +// Type definitions for busboy v0.2.13 +// Project: https://www.npmjs.com/package/busboy +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare namespace busboy { + interface Options { + headers: any; + } + + interface BusboyConfig { + headers?: any; + highWaterMark?: number; + fileHwm?: number; + defCharset?: string; + preservePath?: boolean; + limits?: { + fieldNameSize?: number; + fieldSize?: number; + fields?: number; + fileSize?: number; + files?: number; + parts?: number; + headerPairs?: number; + }; + } + + interface Busboy extends NodeJS.WritableStream { + on(event: 'field', + listener: ( + fieldname: string, + val: any, + fieldnameTruncated: boolean, + valTruncated: boolean, + encoding: string, + mimetype: string) => void): this; + on(event: 'file', + listener: ( + fieldname: string, + file: NodeJS.ReadableStream, + filename: string, + encoding: string, + mimetype: string) => void): this; + on(event: 'finish', callback: () => void): this; + on(event: 'partsLimit', callback: () => void): this; + on(event: 'filesLimit', callback: () => void): this; + on(event: 'fieldsLimit', callback: () => void): this; + on(event: string, listener: Function): this; + } + + interface BusboyConstructor { + new (options: BusboyConfig): Busboy; + } +} + +declare module 'busboy' { + const temp: busboy.BusboyConstructor; + export = temp; +} From 1e4db4e1877c0a224f8fd4a6a9bd143a205ed3ea Mon Sep 17 00:00:00 2001 From: Mykhailo Stadnyk Date: Thu, 15 Sep 2016 16:40:19 +0300 Subject: [PATCH 035/154] Added type definitions for new module canvas-gauges (#11211) * Added type definitions for new module canvas-gauges * definitions re-factored as a ghost module * Typo fixed in url protocol --- canvas-gauges/canvas-gauges-tests.ts | 20 ++ canvas-gauges/canvas-gauges.d.ts | 263 +++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 canvas-gauges/canvas-gauges-tests.ts create mode 100644 canvas-gauges/canvas-gauges.d.ts diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +import { + LinearGaugeOptions, + RadialGaugeOptions, + LinearGauge, + RadialGauge +} from 'canvas-gauges'; + +let linearOptions: LinearGaugeOptions = { + renderTo: document.createElement('canvas') +}; +let radialOptions: RadialGaugeOptions = { + renderTo: 'gauge-id' +}; + +new LinearGauge(linearOptions); +new RadialGauge(radialOptions); + +console.log(document.gauges.length); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare namespace CanvasGauges { + export type RenderTarget = string|HTMLElement; + + export interface AnimationRule { + (percent: number): number; + } + + export interface Highlight { + from: number, + to: number, + color: string + } + + export type MajorTicks = string[]|number[]; + + export interface GenericOptions { + renderTo: RenderTarget, + width?: number, + height?: number, + minValue?: number, + maxValue?: number, + value?: number, + units?: string|boolean, + majorTicks?: MajorTicks, + minorTicks?: number, + strokeTicks?: boolean, + animatedValue?: boolean, + title?: string|boolean, + borders?: boolean, + valueInt?: number, + valueDec?: number, + majorTicksInt?: number, + majorTicksDec?: number, + animation?: boolean, + animationDuration?: number, + animationRule?: string|AnimationRule, + colorPlate?: string, + colorMajorTicks?: string, + colorMinorTicks?: string, + colorTitle?: string, + colorUnits?: string, + colorNumbers?: string, + colorNeedle?: string, + colorNeedleEnd?: string, + colorValueText?: string, + colorValueTextShadow?: string, + colorBorderShadow?: string, + colorBorderOuter?: string, + colorBorderOuterEnd?: string, + colorBorderMiddle?: string, + colorBorderMiddleEnd?: string, + colorBorderInner?: string, + colorBorderInnerEnd?: string, + colorValueBoxRect?: string, + colorValueBoxRectEnd?: string, + colorValueBoxBackground?: string, + colorValueBoxShadow?: string, + colorNeedleShadowUp?: string, + colorNeedleShadowDown?: string, + needle?: boolean, + needleShadow?: boolean, + needleType?: string, + needleStart?: number, + needleEnd?: number, + needleWidth?: number, + borderOuterWidth?: number, + borderMiddleWidth?: number, + borderInnerWidth?: number, + borderShadowWidth?: number, + valueBox?: boolean, + valueBoxStroke?: number, + valueText?: string, + valueTextShadow?: boolean, + valueBoxBorderRadius?: number, + highlights?: Highlight[], + fontNumbers?: string, + fontTitle?: string, + fontUnits?: string, + fontValue?: string, + fontTitleSize?: number, + fontValueSize?: number, + fontUnitsSize?: number, + fontNumbersSize?: number + } + + export interface RadialGaugeOptions extends GenericOptions { + ticksAngle?: number, + startAngle?: number, + colorNeedleCircleOuter?: string, + colorNeedleCircleOuterEnd?: string, + colorNeedleCircleInner?: string, + colorNeedleCircleInnerEnd?: string, + needleCircleSize?: number, + needleCircleInner?: boolean, + needleCircleOuter?: boolean, + animationTarget?: string + } + + export interface LinearGaugeOptions extends GenericOptions { + borderRadius?: number, + barBeginCircle?: number, + barWidth?: number, + barStrokeWidth?: number, + barProgress?: boolean, + colorBar?: string, + colorBarEnd?: string, + colorBarStroke?: string, + colorBarProgress?: string, + colorBarProgressEnd?: string, + tickSide?: string, + needleSide?: string, + numberSide?: string, + ticksWidth?: number, + ticksWidthMinor?: number, + ticksPadding?: number, + barLength?: number + } + + export interface DrawEventCallback { + (percent: number): any; + } + + export interface EndEventCallback { + (): any; + } + + export interface rules { + linear: AnimationRule, + quad: AnimationRule, + dequad: AnimationRule, + quint: AnimationRule, + dequint: AnimationRule, + cycle: AnimationRule, + decycle: AnimationRule, + bounce: AnimationRule, + debounce: AnimationRule, + elastic: AnimationRule, + delastic: AnimationRule + } + + export class Animation { + public duration: number; + public rule: string|AnimationRule; + public draw: DrawEventCallback; + public end: EndEventCallback; + + public static rules: rules; + + constructor(rule?: string|AnimationRule, duration?: number, + draw?: DrawEventCallback, end?: EndEventCallback); + + public animate(draw?: DrawEventCallback, end?: EndEventCallback): any; + public destroy(): any; + } + + export class SmartCanvas { + public element: HTMLCanvasElement; + public elementClone: HTMLCanvasElement; + public context: CanvasRenderingContext2D; + public contextClone: CanvasRenderingContext2D; + public drawWidth: number; + public drawHeight: number; + public drawX: number; + public drawY: number; + public minSide: number; + public width: number; + public height: number; + + constructor(element: HTMLCanvasElement, + width?: number, + height?: number); + + public init(): any; + public onRedraw(): any; + public destroy(): any; + public commit(): SmartCanvas; + public redraw(): SmartCanvas; + + public pixelRatio: number; + public static redraw(): any; + public static collection: Array; + } + + export class DomObserver { + public Type: BaseGauge; + public mutationsObserved: boolean; + public isObservable: boolean; + public options: GenericOptions; + public element: string; + public type: string; + + constructor(options: GenericOptions, + element: string, + type: string); + + public isValidNode(node: Node|HTMLElement): boolean; + public traverse(): any; + public observe(records: MutationRecord[]): any; + public process(node: Node|HTMLElement): BaseGauge; + + public static parse(value: any): any; + public static toDashed(camelCase: string): string; + public static toAttributeName(str: string): string; + static domReady(handler: Function): any; + } + + export abstract class BaseGauge { + public type: BaseGauge; + public options: GenericOptions; + public canvas: SmartCanvas; + public animation: Animation; + public value: number; + + constructor(options: GenericOptions); + + public update(options: GenericOptions): BaseGauge; + public destroy(): any; + public abstract draw(): BaseGauge; + + public static initialize(type: string, options: GenericOptions): any; + } + + export class RadialGauge extends BaseGauge { + public type: RadialGauge; + public options: RadialGaugeOptions; + + constructor(options: RadialGaugeOptions); + + public draw(): RadialGauge; + } + + export class LinearGauge extends BaseGauge { + public type: LinearGauge; + public options: LinearGaugeOptions; + + constructor(options: LinearGaugeOptions); + + public draw(): LinearGauge; + } + + export interface Collection extends Array { + get: (id: number | string) => BaseGauge; + } +} + +declare module 'canvas-gauges' { + export = CanvasGauges; +} + +interface Document { + gauges: CanvasGauges.Collection; +} + +interface Window { + BaseGauge: CanvasGauges.BaseGauge; + RadialGauge: CanvasGauges.RadialGauge; + LinearGauge: CanvasGauges.LinearGauge; +} From 9d66141d077d4f17f148b41fa1adca7a651102e4 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:41:55 +0800 Subject: [PATCH 036/154] [node.d.ts] Update cluster definition (#11235) * Update cluster * Add ; --- node/node.d.ts | 171 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 152 insertions(+), 19 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index e4e66e69ee..346f7e7413 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -741,17 +741,30 @@ declare module "http" { declare module "cluster" { import * as child from "child_process"; import * as events from "events"; + import * as net from "net"; + // interfaces export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv exec?: string; args?: string[]; silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } + + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; } export interface Address { address: string; port: number; - addressType: string; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } export class Worker extends events.EventEmitter { @@ -766,33 +779,153 @@ declare module "cluster" { isDead(): boolean; } - export var settings: ClusterSettings; + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback ?: Function): void; + export function fork(env?: any): Worker; export var isMaster: boolean; export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; export var worker: Worker; export var workers: { [index: string]: Worker }; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; export function listeners(event: string): Function[]; export function emit(event: string, ...args: any[]): boolean; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { From a72353df2416348b0d3f176b8019229c87c064bf Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:42:17 +0800 Subject: [PATCH 037/154] [node-tests.ts] A test should move to events_tests in node (#11237) * A test should move to events_tests in node v6.x * A test should move to events_tests in node v4.x --- node/node-4-tests.ts | 18 ++++++++++-------- node/node-tests.ts | 18 ++++++++++-------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 35fe3553a6..1aebd6d201 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -108,6 +108,16 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -167,14 +177,6 @@ namespace fs_tests { } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// diff --git a/node/node-tests.ts b/node/node-tests.ts index 7e010bc9a3..19048bea9c 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -118,6 +118,16 @@ namespace events_tests { result = emitter.eventNames(); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -212,14 +222,6 @@ namespace fs_tests { } } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// From d6854025495626c9e92efd666032f98313a487ce Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:42:34 +0800 Subject: [PATCH 038/154] [node-tests.ts] The test should test type, not function (#11238) * The test should test type, not function * The test should test type, not function --- node/node-4-tests.ts | 8 ++++---- node/node-tests.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 1aebd6d201..30098021ec 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -906,14 +906,13 @@ namespace errors_tests { /////////////////////////////////////////////////////////// import * as p from "process"; -namespace process_tests{ +namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... var _p: NodeJS.Process = process; _p = p; - assert(p === process); } } @@ -922,8 +921,9 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; } } diff --git a/node/node-tests.ts b/node/node-tests.ts index 19048bea9c..9a2c2e22cd 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1112,14 +1112,13 @@ namespace errors_tests { /////////////////////////////////////////////////////////// import * as p from "process"; -namespace process_tests{ +namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... var _p: NodeJS.Process = process; _p = p; - assert(p === process); } } @@ -1128,9 +1127,10 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; } } From 89030200ceb205da4db2fc56d8e750e9c16be92f Mon Sep 17 00:00:00 2001 From: Jeremy Foster Date: Thu, 15 Sep 2016 06:42:49 -0700 Subject: [PATCH 039/154] add err:any to close, flush, and drain methods (#11239) --- serialport/serialport.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/serialport/serialport.d.ts b/serialport/serialport.d.ts index 53d8a4e92e..60c240bbda 100644 --- a/serialport/serialport.d.ts +++ b/serialport/serialport.d.ts @@ -13,10 +13,10 @@ declare module 'serialport' { pause(): void; resume(): void; disconnected(err: Error): void; - close(callback?: () => void): void; - flush(callback?: () => void): void; + close(callback?: (err:any) => void): void; + flush(callback?: (err:any) => void): void; set(options: SerialPort.setOptions, callback: () => void): void; - drain(callback?: () => void): void; + drain(callback?: (err:any) => void): void; update(options: SerialPort.updateOptions, callback?: () => void): void; static list(callback: (err: string, ports: SerialPort.portConfig[]) => void): void; static parsers: { From 62f98f1a3bce86763366541830b482e4117b5cfb Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:43:21 +0800 Subject: [PATCH 040/154] [node-tests.ts] Clean up http_tests and net_tests (#11240) * Clean up http_tests and net_tests * Clean up fs tests and wrap in namespace --- node/node-4-tests.ts | 69 +++++++++++++++++++++++++------------------- node/node-tests.ts | 69 +++++++++++++++++++++++++------------------- 2 files changed, 80 insertions(+), 58 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 30098021ec..2d84e8f175 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -379,27 +379,18 @@ var tlsOpts: tls.TlsOptions = { }; var tlsSocket = tls.connect(tlsOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -409,20 +400,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -927,3 +927,14 @@ namespace console_tests { _c = c; } } + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} diff --git a/node/node-tests.ts b/node/node-tests.ts index 9a2c2e22cd..ef9f48783f 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -554,27 +554,18 @@ var connOpts: tls.ConnectionOptions = { }; var tlsSocket = tls.connect(connOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -584,20 +575,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -1134,6 +1134,17 @@ namespace console_tests { } } +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * From 48f9040fcc94f007cc7f14415ee4959988543949 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:44:31 +0800 Subject: [PATCH 041/154] [node-tests.ts] Clean up crypto_tests and wrap in namespace (#11242) * Clean up crypto_tests tests and wrap in namespace * Clean up crypto_tests and wrap in namespace * Use let to declares a block scope local variable * Use let to declares a block scope local variable --- node/node-4-tests.ts | 80 ++++++++++++++++++++++++-------------------- node/node-tests.ts | 80 ++++++++++++++++++++++++-------------------- 2 files changed, 86 insertions(+), 74 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 2d84e8f175..2de910db67 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -316,51 +316,57 @@ function stream_readable_pipe_test() { r.close(); } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// diff --git a/node/node-tests.ts b/node/node-tests.ts index ef9f48783f..e0600d936d 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -491,51 +491,57 @@ function simplified_stream_ctor_test() { }) } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// From 4871fb2876696025b0a1704d629378915d7cdd3c Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:45:12 +0800 Subject: [PATCH 042/154] Add listening for http.Server (#11246) --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 346f7e7413..81b13e4e1d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -592,6 +592,7 @@ declare module "http" { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; timeout: number; + listening: boolean; } /** * @deprecated Use IncomingMessage From 9dbdb50546cbec870208edb11e962872128cc1f8 Mon Sep 17 00:00:00 2001 From: Blake Smith Date: Thu, 15 Sep 2016 08:46:59 -0500 Subject: [PATCH 043/154] Updating elasticsearch definition with some of the missing components (#11149) * Updating elasticsearch definition with some of the missing components. (https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-cluster-getsettings) Adding Cluster definitions, one Cat definition. * Correcting header. --- CONTRIBUTORS.md | 1 + elasticsearch/elasticsearch-tests.ts | 40 +++++++++++++ elasticsearch/elasticsearch.d.ts | 90 +++++++++++++++++++++++++++- 3 files changed, 130 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7ebdcc514f..44f0d8e9a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) * [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT) diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 14070aa8cc..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -45,4 +45,44 @@ client.create({ index: 'index', type: 'type' }, (err, repsonse, status) => { +}); + +client.cluster.getSettings({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.health({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.pendingTasks({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.reroute({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.state({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.stats({ + ignore: 1 +}, (err, response) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index ec67e6a59d..e2079b19d0 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,12 +1,14 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); indices: Indices; + cluster: Cluster; + cat: Cat; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; create(params: CreateDocumentParams): PromiseLike; @@ -230,6 +232,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -333,6 +336,91 @@ declare module Elasticsearch { body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + export interface CatHealthOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + h?: string | string[] | boolean; + help?: boolean; + ts?: boolean; + v?: boolean; + } + + export interface Cluster { + getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsOptions): PromiseLike; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + export interface ClusterGetSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterHealthOptions extends GenericParams { + level?: string; // cluster, indices, shards + local?: boolean; + masterTimeout?: number | Date; + waitForActiveShards?: number; + waitForNodes?: string; + waitForRelocatingShards?: number; + waitForStatus?: string; // green, yellow, red + index?: string | string[] | boolean; + } + + export interface ClusterPendingTasksOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + } + + export interface ClusterPutSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterRerouteOptions extends GenericParams { + dryRun?: boolean; + explain?: boolean; + metric?: string | string[] | boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterStateOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: string; // open, closed, none, all (default open) + index?: string | string[] | boolean; + metric?: string | string[] | boolean; + } + + export interface ClusterStatsOptions extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: number | Date; + nodeId?: string | string[] | boolean; + } } declare module "elasticsearch" { From 22a0c3a9a6e798052192b49c104c67057288df6d Mon Sep 17 00:00:00 2001 From: NoHomey Date: Thu, 15 Sep 2016 18:22:20 +0300 Subject: [PATCH 044/154] [jest] updating definition to match latest API reference --- jest/jest-tests.ts | 232 ++++++++++++++++++++++++++++++++++++++++++++- jest/jest.d.ts | 158 ++++++++++++------------------ 2 files changed, 290 insertions(+), 100 deletions(-) diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index f3e33c4061..04fba5ab09 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -37,8 +37,6 @@ describe('fetchCurrentUser', function() { // unmock is the recommended approach for unmocking... jest.unmock('../displayUser.js') -// ...but dontMock also still works. -jest.dontMock('jquery'); describe('displayUser', function() { it('displays a user after a click', function() { @@ -100,6 +98,157 @@ describe('CheckboxWithLabel', function() { }); }); +jest.runAllTicks(); +xdescribe('Hooks and Suits', function () { + let tested: boolean; + + beforeEach(function () { + tested = false; + }); + + afterEach(function () { + tested = true; + }); + + test('tested', function () { + expect(tested).toBeTruthy(); + expect(tested).not.toBeFalsy(); + }); + + fit('tested', function () { + expect(tested).toBeDefined(); + expect(tested).not.toBeUndefined(); + }); + + xit('expect null to be null', function () { + expect(null).toBeNull(); + }); +}); + +describe('compartion', function () { + var sum: (a: number, b: number) => number = require.requireMock('../sum'); + + it('compares is 7 + 2 greater than 3', function () { + expect(sum(7, 2)).toBeGreaterThan(3); + }); + + it('compares is 2 + 7 greater than or equal to 3', function () { + expect(sum(2, 7)).toBeGreaterThanOrEqual(3); + }); + + it('compares is 3 less than 3 + 4', function () { + expect(3).toBeLessThan(sum(3, 4)); + }); + + it('compares is 3 less than or equal to 4 + 3', function () { + expect(3).toBeLessThanOrEqual(sum(4, 3)); + }); + + it('works sanely with simple decimals', function () { + expect(0.2 + 0.1).toBeCloseTo(0.3, 5); + }); +}); + +describe('toThrow API', function () { + function throwTypeError(): void { + throw new TypeError('toThrow Definition was out of date'); + } + + it('throws', function () { + expect(throwTypeError()).toThrow(); + }); + + it('throws TypeError', function () { + expect(throwTypeError()).toThrowError(TypeError); + }); + + it('throws \'Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError(/Definition was out of date/); + }); + + it('throws \'toThorow Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); + }); +}); + +describe('missing tests', function () { + it('creates closures', function () { + class Closure { + private arg: T; + + public constructor(private fn: (arg: T) => void) { + this.fn = fn; + } + + public bind(arg: T): void { + this.arg = arg; + } + + public call(): void { + this.fn(this.arg); + } + } + + type StringClosure = (arg: string) => void; + let spy: jest.Mock = jest.fn(); + let closure: Closure = new Closure(spy); + closure.bind('jest'); + closure.call(); + expect(spy).lastCalledWith('jest'); + expect(spy).toBeCalledWith('jest'); + expect(jest.isMockFunction(spy)).toBeTruthy(); + }); + + it('tests all mising Mocks functionality', function () { + type FruitsGetter = () => Array; + let mock: jest.Mock = jest.fn(); + mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']) + jest.setMock('./../tesks/getFruits', mock); + const getFruits: FruitsGetter = require('./../tesks/getFruits'); + expect(getFruits()).toContain('Orange'); + mock.mockReturnValueOnce(['Apple', 'Plum']); + expect(mock()).not.toContain('Orange'); + mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. + mock.mockClear(); + let thisMock: jest.Mock = jest.fn().mockReturnThis(); + expect(thisMock()).toBe(this); + }); + + it('creates snapshoter', function () { + jest.disableAutomock(); + jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + const render: () => string = require('./render'); + expect(render()).toMatch(/Link/); + jest.enableAutomock(); + }); + + it('runs only pending timers', function () { + jest.useRealTimers(); + setTimeout(() => expect(1).not.toEqual(0), 3000); + jest.runOnlyPendingTimers(); + }); + + it('runs all timers', function () { + jest.clearAllTimers(); + jest.useFakeTimers(); + setTimeout(() => expect(0).not.toEqual(1), 3000); + jest.runAllTimers(); + }); + + it('cleares cache', function () { + const sum1 = require('../sum'); + jest.resetModules(); + const sum2 = require('../sum'); + expect(sum1).not.toBe(sum2); + }) +}); + +describe('toMatchSnapshot', function () { + it('compares snapshots', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); + }); +}); + function testInstances() { var mockFn = jest.fn(); var a = new mockFn(); @@ -123,3 +272,82 @@ function testMockImplementation() { mockFn.mock.calls[0][0] === 0; // true mockFn.mock.calls[1][0] === 1; // true } + +// Test from jest Docs: +describe('genMockFromModule', function () { + // Interfaces: + interface MockFiles { + [index: string]: string; + } + + interface MockedFS { + readdirSync: (dir: string) => string[]; + __setMockFiles: (newMockFiles: MockFiles) => void ; + } + + // ------------------------------------------------------------------------------------ + // FileSummarizer.ts + + const fs = require('fs'); + + function summarizeFilesInDirectorySync(directory: string): string[] { + return fs.readdirSync(directory).map((fileName: string) => ({ + fileName, + directory, + })); + } + + //export default summarizeFilesInDirectorySync; // For sake of compilation + + // ------------------------------------------------------------------------------------ + // __mocks__/fs.js + + const path = require('path'); + + const mockedFS: MockedFS = jest.genMockFromModule('fs'); + + let mockFiles: any = Object.create(null); + function __setMockFiles(newMockFiles: MockFiles): void { + mockFiles = Object.create(null); + for(const file in newMockFiles) { + const dir: string = path.dirname(file); + + if (!mockFiles[dir]) { + mockFiles[dir] = []; + } + mockFiles[dir].push(path.basename(file)); + } + } + + function readdirSync(directoryPath: string): string[] { + return mockFiles[directoryPath] || []; + } + + mockedFS.readdirSync = readdirSync; + mockedFS.__setMockFiles = __setMockFiles; + + //export = mockedFS; // For sake of compilation + // ------------------------------------------------------------------------------------ + // __tests__/FileSummarizer-test.js + + jest.mock('fs'); + + describe('listFilesInDirectorySync', () => { + const MOCK_FILE_INFO: MockFiles = { + '/path/to/file1.js': 'console.log("file1 contents");', + '/path/to/file2.txt': 'file2 contents', + }; + + beforeEach(() => { + // Set up some mocked out file info before each test + (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); + }); + + it('includes all files in the directory in the summary', () => { + const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); + const fileSummary = FileSummarizer('/path/to'); + + expect(fileSummary.length).toBe(2); + }); + }); +}); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index b2484dfcc5..506bd6533d 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,122 +1,79 @@ -// Type definitions for Jest 0.9.0 +// Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana +// Definitions by: Asana , Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare function afterEach(fn: jest.EmptyFunction): void; -declare function beforeEach(fn: jest.EmptyFunction): void; -declare function describe(name: string, fn: jest.EmptyFunction): void; -declare var it: jest.It; -declare function pit(name: string, fn: jest.EmptyFunction): void; - -declare function xdescribe(name: string, fn: jest.EmptyFunction): void; -declare function xit(name: string, fn: jest.EmptyFunction): void; - +declare function afterEach(fn: () => any): void; +declare function beforeEach(fn: () => any): void; +declare function describe(name: string, fn: () => any): void; declare function expect(actual: any): jest.Matchers; +declare function it(name: string, fn: () => any): void; +declare function fit(name: string, fn: () => any): void; -interface NodeRequire { - requireActual(moduleName: string): any; -} +declare function test(name: string, fn: () => any): void; +declare function xdescribe(name: string, fn: () => any): void; +declare function xit(name: string, fn: () => any): void; declare namespace jest { - function addMatchers(matchers: CustomMatcherFactories): void; - function autoMockOff(): void; - function autoMockOn(): void; - function clearAllTimers(): void; - function currentTestPath(): string; - function disableAutomock(): void; - function fn(implementation?: Function): Mock; - function dontMock(moduleName: string): void; - function genMockFromModule(moduleName: string): Mock; - function mock(moduleName: string, factory?: Function): void; - function runAllTicks(): void; - function runAllTimers(): void; - function runOnlyPendingTimers(): void; - function setMock(moduleName: string, moduleExports: T): void; - function unmock(moduleName: string): void; - - interface EmptyFunction { - (): void; - } - interface Matchers { + lastCalledWith(...args: any[]): boolean; not: Matchers; - toThrow(expected?: any): boolean; - toThrowError(expected?: any): boolean; toBe(expected: any): boolean; - toEqual(expected: any): boolean; - toBeFalsy(): boolean; - toBeTruthy(): boolean; - toBeNull(): boolean; - toBeDefined(): boolean; - toBeUndefined(): boolean; - toMatch(expected: RegExp): boolean; - toContain(expected: string): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeGreaterThan(expected: number): boolean; - toBeLessThan(expected: number): boolean; toBeCalled(): boolean; toBeCalledWith(...args: any[]): boolean; - lastCalledWith(...args: any[]): boolean; + toBeCloseTo(expected: number, delta: number): boolean; + toBeDefined(): boolean; + toBeFalsy(): boolean; + toBeGreaterThan(expected: number): boolean; + toBeGreaterThanOrEqual(expected: number): boolean; + toBeLessThan(expected: number): boolean; + toBeLessThanOrEqual(expected: number): boolean; + toBeNull(): boolean; + toBeTruthy(): boolean; + toBeUndefined(): boolean; + toContain(expected: string): boolean; + toEqual(expected: any): boolean; + toMatch(expected: RegExp): boolean; + toMatchSnapshot(): boolean; + toThrow(): boolean; + toThrowError(expected: string | RegExp): boolean; + toThrowError(expected: TFunction): boolean; } - - interface It { - (name: string, fn: EmptyFunction): void; - only(name: string, fn: EmptyFunction): void; - } - - interface Mock { - new (): T; - (...args: any[]): any; // TODO please fix this line! added for TypeScript 1.1.0-1 https://github.com/DefinitelyTyped/DefinitelyTyped/pull/2932 - mock: MockContext; - mockClear(): void; - mockImplementation(fn: Function): Mock; - mockImpl(fn: Function): Mock; - mockReturnThis(): Mock; - mockReturnValue(value: any): Mock; - mockReturnValueOnce(value: any): Mock; - } - + interface MockContext { calls: any[][]; instances: T[]; } - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface MatchersUtil { - equals(a: any, b: any, customTesters?: Array): boolean; - contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomEqualityTester { - (first: any, second: any): boolean; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcher { - compare(actual: T, expected: T): CustomMatcherResult; - compare(actual: any, expected: any): CustomMatcherResult; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherResult { - pass: boolean; - message: string; + interface Mock { + new (): T; + (...args: any[]): any; // Making Mock Callable and fixing: Value of type 'Mock' is not callable. + mock: MockContext; + mockClear(): void; + mockImplementation(fn: Function): Mock; + mockImplementationOnce(fn: Function): Mock; + mockReturnThis(): Mock; + mockReturnValue(value: any): Mock; + mockReturnValueOnce(value: any): Mock; } + + function clearAllTimers(): void; + function disableAutomock(): void; + function enableAutomock(): void; + function fn(implementation?: Function): Mock; + function isMockFunction(fn: Function): boolean; + function genMockFromModule(moduleName: string): T; + function mock(moduleName: string, factory?: Function, options?: {virtual: boolean}): void; + function resetModules(): void; + function runAllTicks(): void; + function runAllTimers(): void; + function runOnlyPendingTimers(): void; + function setMock(moduleName: string, moduleExports: T): void; + function unmock(moduleName: string): void; + function useFakeTimers(): void; + function useRealTimers(): void; // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() interface ArrayLike { @@ -124,3 +81,8 @@ declare namespace jest { [n: number]: T; } } + +interface NodeRequire { + requireActual(moduleName: string): any; + requireMock(moduleName: string): any; +} From 4e6cafda2c6c59c87ebe394f039c63aa35f312ac Mon Sep 17 00:00:00 2001 From: Derek Finlinson Date: Thu, 15 Sep 2016 11:49:51 -0600 Subject: [PATCH 045/154] Fix openQuickCreate signature Fixed openQuickCreate signature which had a callback as the first parameter when it should just return a XrmPromise. --- xrm/xrm.d.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index 824c91ba0c..2e4856e0c7 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -160,8 +160,6 @@ declare namespace Xrm /** * Opens quick create. * - * @param {Function} callback The function that will be called when a record is created. This - * function is passed a LookupValue object as a parameter. * @param {string} entityLogicalName The logical name of the entity to create. * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values * based on mapped attribute values. @@ -170,10 +168,9 @@ declare namespace Xrm * error. */ openQuickCreate( - callback: ( recordReference: Page.LookupValue ) => void, entityLogicalName: string, createFromEntity?: Page.LookupValue, - parameters?: Utility.OpenParameters ): void; + parameters?: Utility.OpenParameters ): Async.XrmPromise; /** * Opens an entity form. @@ -1477,11 +1474,11 @@ declare namespace Xrm * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an * entity. * - * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with + * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with * dictionary properties where the name of the property is the Id of the * business process flow and the value of the property is the name of the * business process flow. - * + * * The enabled processes are filtered according to the user’s privileges. The * list of enabled processes is the same ones a user can see in the UI if they * want to change the process manually. @@ -1501,7 +1498,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -1515,7 +1512,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -2587,4 +2584,4 @@ declare namespace XrmEnum SystemView = 1039, UserView = 4230 } -} \ No newline at end of file +} From 34cc2ed80a7fe9f75c36d0f89c336234991fe320 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Fri, 16 Sep 2016 02:15:14 +0800 Subject: [PATCH 046/154] Create pug-test.ts --- pug/pug-test.ts | 103 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 pug/pug-test.ts diff --git a/pug/pug-test.ts b/pug/pug-test.ts new file mode 100644 index 0000000000..5ba7d9ad06 --- /dev/null +++ b/pug/pug-test.ts @@ -0,0 +1,103 @@ +/// +import * as pug from 'pug'; + + +//////////////////////////////////////////////////////////// +/// Options https://pugjs.org/api/reference.html#options /// +//////////////////////////////////////////////////////////// +namespace options_tests { + let opts: pug.Options; + let str = 'string' + let bool = false; + let strArray = ['string']; + + opts.filename = str; + + opts.basedir = str; + + opts.doctype = str; + + opts.pretty = str; + opts.pretty = bool; + + opts.filters = {}; + + opts.self = bool; + + opts.debug = bool; + opts.compileDebug = bool; + + opts.globals = strArray; + + opts.cache = bool; + + opts.inlineRuntimeFunctions = bool; + + opts.name = str; +} + +//////////////////////////////////////////////////////////// +/// Methods https://pugjs.org/api/reference.html#methods /// +//////////////////////////////////////////////////////////// +namespace methods_tests { + let source = `p #{ name } 's Pug source code!`; + let path = "foo.pug"; + let compileTemplate: pug.compileTemplate; + let template: string; + let clientFunctionString: pug.ClientFunctionString; + let str: string; + + { + /// pug.compile(source, ?options) https://pugjs.org/api/reference.html#pugcompilesource-options + compileTemplate = pug.compile(source); + template = compileTemplate(); + } + + { + /// pug.compileFile(path, ?options) https://pugjs.org/api/reference.html#pugcompilefilepath-options + compileTemplate = pug.compileFile(path); + template = compileTemplate(); + } + + { + /// pug.compileClient(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientsource-options + clientFunctionString = pug.compileClient(path); + str = pug.compileClient(path); + } + + { + /// pug.compileClientWithDependenciesTracked(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientwithdependenciestrackedsource-options + let obj = pug.compileClientWithDependenciesTracked(source); + clientFunctionString = obj.body; + str = obj.body; + let strArray: string[] = obj.dependencies; + } + + { + /// pug.compileFileClient(path, ?options) https://pugjs.org/api/reference.html#pugcompilefileclientpath-options + clientFunctionString = pug.compileFileClient(path); + str = pug.compileFileClient(path); + } + + { + /// pug.render(source, ?options, ?callback) https://pugjs.org/api/reference.html#pugrendersource-options-callback + str = pug.render(source); + + // test type for callback paraments + pug.render(source, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } + + { + /// pug.renderFile(path, ?options, ?callback) https://pugjs.org/api/reference.html#pugrenderfilepath-options-callback + str = pug.renderFile(path); + + // test type for callback paraments + pug.renderFile(path, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } +} From 1b803f972a8edfcd8341520f195e7354fa091ec2 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 12:49:30 +0200 Subject: [PATCH 047/154] Added definition file for randomColor --- randomColor/randomColor-tests.ts | 2 ++ randomColor/randomColor.d.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 randomColor/randomColor-tests.ts create mode 100644 randomColor/randomColor.d.ts diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts new file mode 100644 index 0000000000..274768ebc1 --- /dev/null +++ b/randomColor/randomColor-tests.ts @@ -0,0 +1,2 @@ +/// + diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts new file mode 100644 index 0000000000..e439e2d77d --- /dev/null +++ b/randomColor/randomColor.d.ts @@ -0,0 +1,30 @@ +// Type definitions for randomColor 0.4.1 +// Project: https://github.com/davidmerfield/randomColor +// Definitions by: Mathias Feitzinger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace RandomColor { + + interface RandomColorStatic { + + () : string; + + (options : randomColorOptions): string; + +} + +interface randomColorOptions { + hue? : string; + luminosity? : string; + count? : string; + seed?: string; + format?: string; + } +} + + +declare var randomColor: RandomColor.RandomColorStatic; + +declare module 'randomColor' { + export = randomColor; +} \ No newline at end of file From 300d30753459bbd6fe6b53b61e44e21e3669fc97 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 12:58:59 +0200 Subject: [PATCH 048/154] added test for randomColor --- randomColor/randomColor-tests.ts | 38 ++++++++++++++++++++++++++++++++ randomColor/randomColor.d.ts | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts index 274768ebc1..69b617615e 100644 --- a/randomColor/randomColor-tests.ts +++ b/randomColor/randomColor-tests.ts @@ -1,2 +1,40 @@ /// +// Returns a hex code for an attractive color +randomColor(); + +// Returns an array of ten green colors +randomColor({ + count: 10, + hue: 'green' +}); + +// Returns a hex code for a light blue +randomColor({ + luminosity: 'light', + hue: 'blue' +}); + +// Returns a hex code for a 'truly random' color +randomColor({ + luminosity: 'random', + hue: 'random' +}); + +// Returns a bright color in RGB +randomColor({ + luminosity: 'bright', + format: 'rgb' // e.g. 'rgb(225,200,20)' +}); + +// Returns a dark RGB color with random alpha +randomColor({ + luminosity: 'dark', + format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)' +}); + +// Returns a light HSL color with random alpha +randomColor({ + luminosity: 'light', + format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' +}); \ No newline at end of file diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index e439e2d77d..81f43a0228 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -16,7 +16,7 @@ declare namespace RandomColor { interface randomColorOptions { hue? : string; luminosity? : string; - count? : string; + count? : string | number; seed?: string; format?: string; } From 1175068a71da6baf10fffaf08df4fa8c32ebb6a9 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 13:14:08 +0200 Subject: [PATCH 049/154] styling for randomColor --- randomColor/randomColor.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index 81f43a0228..1c52f39be1 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -10,7 +10,6 @@ declare namespace RandomColor { () : string; (options : randomColorOptions): string; - } interface randomColorOptions { @@ -22,7 +21,6 @@ interface randomColorOptions { } } - declare var randomColor: RandomColor.RandomColorStatic; declare module 'randomColor' { From b5e3b1987f6cbee9627bdbd845e0e9bf71325125 Mon Sep 17 00:00:00 2001 From: Ulrich Buchgraber Date: Fri, 16 Sep 2016 18:17:22 +0200 Subject: [PATCH 050/154] Simplify typings by employing "polymorphic this types" for clone()/copy() methods Note: This also solves TS 2.0 --strictNullChecks errors. --- threejs/three-canvasrenderer.d.ts | 1 - threejs/three.d.ts | 221 +++++++++--------------------- 2 files changed, 63 insertions(+), 159 deletions(-) diff --git a/threejs/three-canvasrenderer.d.ts b/threejs/three-canvasrenderer.d.ts index 2d2d9e4930..7dba387da9 100644 --- a/threejs/three-canvasrenderer.d.ts +++ b/threejs/three-canvasrenderer.d.ts @@ -17,7 +17,6 @@ declare namespace THREE { color: Color; program(context: any, color: Color): void; - clone(): SpriteCanvasMaterial; } export interface CanvasRendererParameters { diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 9e70f1e898..830edbf864 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -461,9 +461,6 @@ declare namespace THREE { * @param vector point to look at */ lookAt(vector: Vector3): void; - - clone(): Camera; - copy(camera?: Camera): Camera; } export class CubeCamera extends Object3D { @@ -540,8 +537,6 @@ declare namespace THREE { updateProjectionMatrix(): void; setViewOffset(fullWidth: number, fullHeight: number, offsetX: number, offsetY: number, width: number, height: number): void; clearViewOffset(): void; - clone(): OrthographicCamera; - copy(source: OrthographicCamera): OrthographicCamera; toJSON(meta?: any): any; } @@ -646,7 +641,6 @@ declare namespace THREE { * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; - clone(): PerspectiveCamera; toJSON(meta?: any): any; // deprecated @@ -682,8 +676,8 @@ declare namespace THREE { count: number; setDynamic(dynamic: boolean): BufferAttribute; - clone(): BufferAttribute; - copy(source: BufferAttribute): BufferAttribute; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: BufferAttribute, index2: number): BufferAttribute; copyArray(array: ArrayLike): BufferAttribute; copyColorsArray(colors: {r: number, g: number, b: number}[]): BufferAttribute; @@ -703,7 +697,6 @@ declare namespace THREE { setXY(index: number, x: number, y: number): BufferAttribute; setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; - clone(): BufferAttribute; length: number; // deprecated, use count } @@ -834,8 +827,8 @@ declare namespace THREE { toNonIndexed(): BufferGeometry; toJSON(): any; - clone(): BufferGeometry; - copy(source: BufferGeometry): BufferGeometry; + clone(): this; + copy(source: this): this; /** * Disposes the object from memory. @@ -1086,8 +1079,8 @@ declare namespace THREE { */ materialIndex: number; - clone(): Face3; - copy(source: Face3): Face3; + clone(): this; + copy(source: this): this; } export class Face4 extends Face3 {} // deprecated, use Face3 @@ -1308,9 +1301,9 @@ declare namespace THREE { /** * Creates a new clone of the Geometry. */ - clone(): Geometry; + clone(): this; - copy(source: Geometry): Geometry; + copy(source: this): this; /** * Removes The object from memory. @@ -1343,9 +1336,6 @@ declare namespace THREE { constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedBufferAttribute; - copy(source: InstancedBufferAttribute): InstancedBufferAttribute; } /** @@ -1358,8 +1348,6 @@ declare namespace THREE { maxInstancedCount: number; addGroup(start: number, count: number, instances: number): void; - clone(): InstancedBufferGeometry; - copy(source: InstancedBufferGeometry): InstancedBufferGeometry; } /** @@ -1378,11 +1366,11 @@ declare namespace THREE { needsUpdate: boolean; setDynamic(dynamic: boolean): InterleavedBuffer; - clone(): InterleavedBuffer; - copy(source: InterleavedBuffer): InterleavedBuffer; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: InterleavedBufferAttribute, index2: number): InterleavedBuffer; set(value: ArrayLike, index: number): InterleavedBuffer; - clone(): InterleavedBuffer; + clone(): this; } /** @@ -1392,9 +1380,6 @@ declare namespace THREE { constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedInterleavedBuffer; - copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; } /** @@ -1686,14 +1671,14 @@ declare namespace THREE { toJSON(meta?: { geometries: any, materials: any, textures: any, images: any }): any; - clone(recursive?: boolean): Object3D; + clone(recursive?: boolean): this; /** * * @param object * @param recursive */ - copy(source: Object3D, recursive?: boolean): Object3D; + copy(source: this, recursive?: boolean): this; // deprecated eulerOrder: string; @@ -1777,9 +1762,6 @@ declare namespace THREE { shadowBias: any; // deprecated, use shadow.bias shadowMapWidth: any; // deprecated, use shadow.mapSize.width shadowMapHeight: any; // deprecated, use shadow.mapSize.height - - copy(source: Light): Light; - clone(recursive?: boolean): Light; } export class LightShadow { @@ -1792,8 +1774,8 @@ declare namespace THREE { map: RenderTarget; matrix: Matrix4; - copy(source: LightShadow): LightShadow; - clone(recursive?: boolean): LightShadow; + copy(source: this): this; + clone(recursive?: boolean): this; toJSON(): any; } @@ -1814,9 +1796,6 @@ declare namespace THREE { constructor(hex?: number|string, intensity?: number); castShadow: boolean; - - copy(source: AmbientLight): AmbientLight; - clone(recursive?: boolean): AmbientLight; } /** @@ -1845,9 +1824,6 @@ declare namespace THREE { intensity: number; shadow: LightShadow; - - copy(source: DirectionalLight): DirectionalLight; - clone(recursive?: boolean): HemisphereLight; } export class DirectionalLightShadow extends LightShadow {} @@ -1857,9 +1833,6 @@ declare namespace THREE { groundColor: Color; intensity: number; - - copy(source: HemisphereLight): HemisphereLight; - clone(recursive?: boolean): HemisphereLight; } /** @@ -1888,9 +1861,6 @@ declare namespace THREE { decay: number; shadow: LightShadow; power: number; - - copy(source: PointLight): PointLight; - clone(recursive?: boolean): PointLight; } /** @@ -1933,9 +1903,6 @@ declare namespace THREE { shadow: SpotLightShadow; power: number; penumbra: number; - - clone(recursive?: boolean): SpotLight; - copy(source: PointLight): SpotLight; } export class SpotLightShadow extends LightShadow { @@ -2359,8 +2326,8 @@ declare namespace THREE { setValues(parameters: MaterialParameters): void; toJSON(meta?: any): any; - clone(): Material; - copy(source: Material): Material; + clone(): this; + copy(source: this): this; update(): void; dispose(): void; @@ -2384,8 +2351,6 @@ declare namespace THREE { linejoin: string; setValues(parameters: LineBasicMaterialParameters): void; - clone(): LineBasicMaterial; - copy(source: LineBasicMaterial): LineBasicMaterial; } export interface LineDashedMaterialParameters extends MaterialParameters { @@ -2406,8 +2371,6 @@ declare namespace THREE { gapSize: number; setValues(parameters: LineDashedMaterialParameters): void; - clone(): LineDashedMaterial; - copy(source: LineDashedMaterial): LineDashedMaterial; } /** @@ -2456,8 +2419,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshBasicMaterialParameters): void; - clone(): MeshBasicMaterial; - copy(source: MeshBasicMaterial): MeshBasicMaterial; } export interface MeshDepthMaterialParameters extends MaterialParameters { @@ -2472,8 +2433,6 @@ declare namespace THREE { wireframeLinewidth: number; setValues(parameters: MeshDepthMaterialParameters): void; - clone(): MeshDepthMaterial; - copy(source: MeshDepthMaterial): MeshDepthMaterial; } export interface MeshLambertMaterialParameters extends MaterialParameters { @@ -2528,8 +2487,6 @@ declare namespace THREE { morphNormals: boolean; setValues(parameters: MeshLambertMaterialParameters): void; - clone(): MeshLambertMaterial; - copy(source: MeshLambertMaterial): MeshLambertMaterial; } export interface MeshStandardMaterialParameters extends MaterialParameters { @@ -2599,8 +2556,6 @@ declare namespace THREE { morphNormals: boolean; setValues(parameters: MeshStandardMaterialParameters): void; - clone(): MeshStandardMaterial; - copy(source: MeshStandardMaterial): MeshStandardMaterial; } export interface MeshNormalMaterialParameters extends MaterialParameters { @@ -2619,8 +2574,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshNormalMaterialParameters): void; - clone(): MeshNormalMaterial; - copy(source: MeshNormalMaterial): MeshNormalMaterial; } export interface MeshPhongMaterialParameters extends MaterialParameters { @@ -2696,8 +2649,6 @@ declare namespace THREE { metal: boolean; // deprecated setValues(parameters: MeshPhongMaterialParameters): void; - clone(): MeshPhongMaterial; - copy(source: MeshPhongMaterial): MeshPhongMaterial; } export interface MeshPhysicalMaterialParameters extends MeshStandardMaterialParameters { @@ -2723,7 +2674,6 @@ declare namespace THREE { materials: Material[]; toJSON(meta: any): any; - clone(): MultiMaterial; } export class MeshFaceMaterial extends MultiMaterial {} // deprecated, use MultiMaterial @@ -2744,8 +2694,6 @@ declare namespace THREE { sizeAttenuation: boolean; setValues(parameters: PointsMaterialParameters): void; - clone(): PointsMaterial; - copy(source: PointsMaterial): PointsMaterial; } export class PointCloudMaterial extends PointsMaterial {} // deprecated @@ -2788,8 +2736,6 @@ declare namespace THREE { index0AttributeName: string; setValues(parameters: ShaderMaterialParameters): void; - clone(): ShaderMaterial; - copy(source: ShaderMaterial): ShaderMaterial; toJSON(meta: any): any; } @@ -2811,8 +2757,6 @@ declare namespace THREE { rotation: number; setValues(parameters: SpriteMaterialParameters): void; - clone(): SpriteMaterial; - copy(source: SpriteMaterial): SpriteMaterial; } export class ShadowMaterial extends ShaderMaterial { @@ -2830,8 +2774,8 @@ declare namespace THREE { set(min: Vector2, max: Vector2): Box2; setFromPoints(points: Vector2[]): Box2; setFromCenterAndSize(center: Vector2, size: Vector2): Box2; - clone(): Box2; - copy(box: Box2): Box2; + clone(): this; + copy(box: this): this; makeEmpty(): Box2; isEmpty(): boolean; center(optionalTarget?: Vector2): Vector2; @@ -2865,8 +2809,8 @@ declare namespace THREE { setFromPoints(points: Vector3[]): Box3; setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; - clone(): Box3; - copy(box: Box3): Box3; + clone(): this; + copy(box: this): this; makeEmpty(): Box3; isEmpty(): boolean; center(optionalTarget?: Vector3): Vector3; @@ -2962,13 +2906,13 @@ declare namespace THREE { /** * Clones this color. */ - clone(): Color; + clone(): this; /** * Copies given color. * @param color Color to copy. */ - copy(color: Color): Color; + copy(color: this): this; /** * Copies given color making conversion from gamma to linear space. @@ -3184,8 +3128,8 @@ declare namespace THREE { onChangeCallback: Function; set(x: number, y: number, z: number, order?: string): Euler; - clone(): Euler; - copy(euler: Euler): Euler; + clone(): this; + copy(euler: this): this; setFromRotationMatrix(m: Matrix4, order?: string, update?: boolean): Euler; setFromQuaternion(q: Quaternion, order?: string, update?: boolean): Euler; setFromVector3( v: Vector3, order?: string ): Euler; @@ -3212,8 +3156,8 @@ declare namespace THREE { planes: Plane[]; set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; - clone(): Frustum; - copy(frustum: Frustum): Frustum; + clone(): this; + copy(frustum: this): this; setFromMatrix(m: Matrix4): Frustum; intersectsObject(object: Object3D): boolean; intersectsObject(sprite: Sprite): boolean; @@ -3229,8 +3173,8 @@ declare namespace THREE { end: Vector3; set(start?: Vector3, end?: Vector3): Line3; - clone(): Line3; - copy(line: Line3): Line3; + clone(): this; + copy(line: this): this; center(optionalTarget?: Vector3): Vector3; delta(optionalTarget?: Vector3): Vector3; distanceSq(): number; @@ -3326,7 +3270,7 @@ declare namespace THREE { /** * copy(m:T):T; */ - copy(m: Matrix): Matrix; + copy(m: this): this; /** * multiplyScalar(s:number):T; @@ -3348,7 +3292,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Matrix; + clone(): this; } /** @@ -3367,8 +3311,8 @@ declare namespace THREE { set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; identity(): Matrix3; - clone(): Matrix3; - copy(m: Matrix3): Matrix3; + clone(): this; + copy(m: this): this; setFromMatrix4(m: Matrix4): Matrix3; applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer(buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; @@ -3431,8 +3375,8 @@ declare namespace THREE { * Resets this matrix to identity. */ identity(): Matrix4; - clone(): Matrix4; - copy(m: Matrix4): Matrix4; + clone(): this; + copy(m: this): this; copyPosition(m: Matrix4): Matrix4; extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; @@ -3593,8 +3537,8 @@ declare namespace THREE { setComponents(x: number, y: number, z: number, w: number): Plane; setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; - clone(): Plane; - copy(plane: Plane): Plane; + clone(): this; + copy(plane: this): this; normalize(): Plane; negate(): Plane; distanceToPoint(point: Vector3): number; @@ -3617,8 +3561,8 @@ declare namespace THREE { constructor(radius?: number, phi?: number, theta?: number); set(radius: number, phi: number, theta: number): Spherical; - clone(): Spherical; - copy(other: Spherical): Spherical; + clone(): this; + copy(other: this): this; makeSafe(): void; setFromVector3(vec3: Vector3): Spherical; } @@ -3654,12 +3598,12 @@ declare namespace THREE { /** * Clones this quaternion. */ - clone(): Quaternion; + clone(): this; /** * Copies values of q to this quaternion. */ - copy(q: Quaternion): Quaternion; + copy(q: this): this; /** * Sets this quaternion from rotation specified by Euler angles. @@ -3739,8 +3683,8 @@ declare namespace THREE { direction: Vector3; set(origin: Vector3, direction: Vector3): Ray; - clone(): Ray; - copy(ray: Ray): Ray; + clone(): this; + copy(ray: this): this; at(t: number, optionalTarget?: Vector3): Vector3; lookAt(v: Vector3): Vector3; recast(t: number): Ray; @@ -3773,8 +3717,8 @@ declare namespace THREE { set(center: Vector3, radius: number): Sphere; setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; - clone(): Sphere; - copy(sphere: Sphere): Sphere; + clone(): this; + copy(sphere: this): this; empty(): boolean; containsPoint(point: Vector3): boolean; distanceToPoint(point: Vector3): number; @@ -3850,8 +3794,8 @@ declare namespace THREE { set(a: Vector3, b: Vector3, c: Vector3): Triangle; setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; - clone(): Triangle; - copy(triangle: Triangle): Triangle; + clone(): this; + copy(triangle: this): this; area(): number; midpoint(optionalTarget?: Vector3): Vector3; normal(optionalTarget?: Vector3): Vector3; @@ -3885,7 +3829,7 @@ declare namespace THREE { /** * copy(v:T):T; */ - copy(v: Vector): Vector; + copy(v: this): this; /** * add(v:T):T; @@ -3974,7 +3918,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Vector; + clone(): this; } /** @@ -4019,11 +3963,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector2; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector2): Vector2; + copy(v: this): this; /** * Adds v to this vector. @@ -4185,11 +4129,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector3; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector3): Vector3; + copy(v: this): this; /** * Adds v to this vector. @@ -4381,11 +4325,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector4; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector4): Vector4; + copy(v: this): this; /** * Adds v to this vector. @@ -4533,9 +4477,6 @@ declare namespace THREE { constructor(skin: SkinnedMesh); skin: SkinnedMesh; - - clone(): Bone; - copy(source: Bone): Bone; } export class Group extends Object3D { @@ -4551,8 +4492,6 @@ declare namespace THREE { getObjectForDistance(distance: number): Object3D; raycast(raycaster: Raycaster, intersects: any): void; update(camera: Camera): void; - clone(): LOD; - copy(source: LOD): LOD; toJSON(meta: any): any; // deprecated @@ -4583,8 +4522,6 @@ declare namespace THREE { add(object: Object3D): void; add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; updateLensFlares(): void; - clone(): LensFlare; - copy(source: LensFlare): LensFlare; } export class Line extends Object3D { @@ -4598,8 +4535,6 @@ declare namespace THREE { material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial raycast(raycaster: Raycaster, intersects: any): void; - clone(): Line; - copy(source: Line): Line; } export const LineStrip: number; // deprecated @@ -4611,9 +4546,6 @@ declare namespace THREE { material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, mode?: number ); - - clone(): LineSegments; - copy(source: LineSegments): LineSegments; } enum LineMode {} @@ -4630,8 +4562,6 @@ declare namespace THREE { updateMorphTargets(): void; getMorphTargetIndexByName(name: string): number; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Mesh; - copy(source: Mesh): Mesh; } /** @@ -4661,8 +4591,6 @@ declare namespace THREE { material: Material; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Points; - copy(source: Points): Points; } export class PointCloud extends Points {} // deprecated @@ -4683,7 +4611,7 @@ declare namespace THREE { calculateInverses(bone: Bone): void; pose(): void; update(): void; - clone(): Skeleton; + clone(): this; } export class SkinnedMesh extends Mesh { @@ -4704,8 +4632,6 @@ declare namespace THREE { pose(): void; normalizeSkinWeights(): void; updateMatrixWorld(force?: boolean): void; - clone(): SkinnedMesh; - copy(source: SkinnedMesh): SkinnedMesh; } export class Sprite extends Object3D { @@ -4715,8 +4641,6 @@ declare namespace THREE { material: SpriteMaterial; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Sprite; - copy(source: Sprite): Sprite; } export class Particle extends Sprite {} // deprecated @@ -5048,8 +4972,8 @@ declare namespace THREE { generateMipmaps: any; // deprecated, use texture.generateMipmaps setSize(width: number, height: number): void; - clone(): WebGLRenderTarget; - copy(source: WebGLRenderTarget): WebGLRenderTarget; + clone(): this; + copy(source: this): this; dispose(): void; } @@ -5596,14 +5520,13 @@ declare namespace THREE { autoUpdate: boolean; background: any; - copy(source: Scene, recursive?: boolean): Scene; toJSON(meta?: any): any; } export interface IFog { name: string; color: Color; - clone(): IFog; + clone(): this; toJSON(): any; } @@ -5631,7 +5554,7 @@ declare namespace THREE { */ far: number; - clone(): Fog; + clone(): this; toJSON(): any; } @@ -5650,7 +5573,7 @@ declare namespace THREE { */ density: number; - clone(): FogExp2; + clone(): this; toJSON(): any; } @@ -5698,8 +5621,8 @@ declare namespace THREE { static DEFAULT_IMAGE: any; static DEFAULT_MAPPING: any; - clone(): Texture; - copy(source: Texture): Texture; + clone(): this; + copy(source: this): this; toJSON(meta: any): any; dispose(): void; transformUv(uv: Vector): void; @@ -5733,9 +5656,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): CanvasTexture; - copy(source: CanvasTexture): CanvasTexture; } export class CubeTexture extends Texture { @@ -5753,8 +5673,6 @@ declare namespace THREE { ); images: any; // returns and sets the value of Texture.image in the codde ? - - copy(source: CubeTexture): CubeTexture; } export class CompressedTexture extends Texture { @@ -5774,9 +5692,6 @@ declare namespace THREE { ); image: { width: number; height: number; }; - - clone(): CompressedTexture; - copy(source: CompressedTexture): CompressedTexture; } export class DataTexture extends Texture { @@ -5796,9 +5711,6 @@ declare namespace THREE { ); image: { data: ImageData; width: number; height: number; }; - - clone(): DataTexture; - copy(source: DataTexture): DataTexture; } export class VideoTexture extends Texture { @@ -5813,9 +5725,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): VideoTexture; - copy(source: VideoTexture): VideoTexture; } // Extras ///////////////////////////////////////////////////////////////////// @@ -6221,8 +6130,6 @@ declare namespace THREE { heightSegments: number; depthSegments: number; }; - - clone(): BoxGeometry; } export class CubeGeometry extends BoxGeometry {} // deprecated, use BoxGeometry @@ -6306,8 +6213,6 @@ declare namespace THREE { export class EdgesGeometry extends BufferGeometry { constructor(geometry: BufferGeometry, thresholdAngle: number); - - clone(): EdgesGeometry; } export class ExtrudeGeometry extends Geometry { From 7c9f3114a756f052ca10caba615540d7b5eb19be Mon Sep 17 00:00:00 2001 From: Dave Dunkin Date: Fri, 16 Sep 2016 12:10:31 -0700 Subject: [PATCH 051/154] Fix elasticsearch get, mget, msearch responses. (#11259) * Fix elasticsearch get, mget, msearch responses. * Fix contributor github links. --- elasticsearch/elasticsearch.d.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index e2079b19d0..d983817869 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,6 +1,6 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { @@ -15,14 +15,14 @@ declare module Elasticsearch { create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; - get(params: GetParams, callback: (error: any, response: any) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams): PromiseLike>; - msearch(params: MSearchParams, callback: (error: any, response: any) => void): void; - msearch(params: MSearchParams): PromiseLike>; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): PromiseLike>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): PromiseLike>; ping(params: PingParams): PromiseLike; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; scroll(params: ScrollParams): PromiseLike; @@ -196,7 +196,8 @@ declare module Elasticsearch { versionType?: string; } - export interface GetResponse extends GenericParams { + export interface GetResponse { + _index: string; _type: string; _id: string; _version: number; @@ -279,6 +280,10 @@ declare module Elasticsearch { search_type?: string; } + export interface MSearchResponse { + responses?: SearchResponse[]; + } + export interface MGetParams extends GenericParams { fields?: string | string[] | Boolean; preference?: string; @@ -290,6 +295,10 @@ declare module Elasticsearch { type?: string; } + export interface MGetResponse { + docs?: GetResponse[]; + } + export interface IndicesIndexExitsParams extends GenericParams { index: string | string[] | boolean; ignoreUnavailable?: boolean; From e0a4b59de6eea0e2c70b0a403a6566d402f0e1d3 Mon Sep 17 00:00:00 2001 From: Julien Sergent Date: Sat, 17 Sep 2016 00:05:58 +0200 Subject: [PATCH 052/154] Update facebook-js-sdk.d.ts --- facebook-js-sdk/facebook-js-sdk.d.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/facebook-js-sdk/facebook-js-sdk.d.ts b/facebook-js-sdk/facebook-js-sdk.d.ts index 5353353911..bee34f0a2c 100644 --- a/facebook-js-sdk/facebook-js-sdk.d.ts +++ b/facebook-js-sdk/facebook-js-sdk.d.ts @@ -8,10 +8,11 @@ declare var FB: fb.FacebookStatic; declare namespace facebook { interface FacebookStatic { - // api: any; - // AppEvents: any; - // Canvas: any; - // Event: any; + api: any; + AppEvents: any; + Canvas: any; + Event: any; + /** * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. @@ -25,7 +26,7 @@ declare namespace facebook { * * @param callback function to handle the response. */ - getLoginStatus(callback: (response: AuthResponse) => void): void; + getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void; /** * The method FB.init() is used to initialize and setup the SDK. * @@ -49,8 +50,9 @@ declare namespace facebook { * @param callback function to handle the response */ logout(callback: (response: AuthResponse) => void): void; - // ui: any; - // XFBML: any; + + ui: any; + XFBML: any; } interface InitParams { From bb69a3320f934d39d1ce65a024b9b3464283fe02 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sat, 17 Sep 2016 13:28:12 +0800 Subject: [PATCH 053/154] Delete pug-test.ts --- pug/pug-test.ts | 103 ------------------------------------------------ 1 file changed, 103 deletions(-) delete mode 100644 pug/pug-test.ts diff --git a/pug/pug-test.ts b/pug/pug-test.ts deleted file mode 100644 index 5ba7d9ad06..0000000000 --- a/pug/pug-test.ts +++ /dev/null @@ -1,103 +0,0 @@ -/// -import * as pug from 'pug'; - - -//////////////////////////////////////////////////////////// -/// Options https://pugjs.org/api/reference.html#options /// -//////////////////////////////////////////////////////////// -namespace options_tests { - let opts: pug.Options; - let str = 'string' - let bool = false; - let strArray = ['string']; - - opts.filename = str; - - opts.basedir = str; - - opts.doctype = str; - - opts.pretty = str; - opts.pretty = bool; - - opts.filters = {}; - - opts.self = bool; - - opts.debug = bool; - opts.compileDebug = bool; - - opts.globals = strArray; - - opts.cache = bool; - - opts.inlineRuntimeFunctions = bool; - - opts.name = str; -} - -//////////////////////////////////////////////////////////// -/// Methods https://pugjs.org/api/reference.html#methods /// -//////////////////////////////////////////////////////////// -namespace methods_tests { - let source = `p #{ name } 's Pug source code!`; - let path = "foo.pug"; - let compileTemplate: pug.compileTemplate; - let template: string; - let clientFunctionString: pug.ClientFunctionString; - let str: string; - - { - /// pug.compile(source, ?options) https://pugjs.org/api/reference.html#pugcompilesource-options - compileTemplate = pug.compile(source); - template = compileTemplate(); - } - - { - /// pug.compileFile(path, ?options) https://pugjs.org/api/reference.html#pugcompilefilepath-options - compileTemplate = pug.compileFile(path); - template = compileTemplate(); - } - - { - /// pug.compileClient(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientsource-options - clientFunctionString = pug.compileClient(path); - str = pug.compileClient(path); - } - - { - /// pug.compileClientWithDependenciesTracked(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientwithdependenciestrackedsource-options - let obj = pug.compileClientWithDependenciesTracked(source); - clientFunctionString = obj.body; - str = obj.body; - let strArray: string[] = obj.dependencies; - } - - { - /// pug.compileFileClient(path, ?options) https://pugjs.org/api/reference.html#pugcompilefileclientpath-options - clientFunctionString = pug.compileFileClient(path); - str = pug.compileFileClient(path); - } - - { - /// pug.render(source, ?options, ?callback) https://pugjs.org/api/reference.html#pugrendersource-options-callback - str = pug.render(source); - - // test type for callback paraments - pug.render(source, {}, (err, html) => { - let e: Error = err; - str = html; - }); - } - - { - /// pug.renderFile(path, ?options, ?callback) https://pugjs.org/api/reference.html#pugrenderfilepath-options-callback - str = pug.renderFile(path); - - // test type for callback paraments - pug.renderFile(path, {}, (err, html) => { - let e: Error = err; - str = html; - }); - } -} From 9d4d9924f1a5562c61421d82d8f4f474a425fb04 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:10:19 +0800 Subject: [PATCH 054/154] [node] Clean up tls_tests and wrap in namespace (#11248) * Clean up tls_tests and wrap in namespace for v6.x * Clean up tls_tests and wrap in namespace for v4.x --- node/node-4-tests.ts | 28 +++++++++++++++------------- node/node-tests.ts | 28 +++++++++++++++------------- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 2de910db67..66fc18ce24 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -369,21 +369,23 @@ namespace crypto_tests { } } -//////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; +namespace tls_tests { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + var blah = ctx.context; -var tlsOpts: tls.TlsOptions = { - host: "127.0.0.1", - port: 55 -}; -var tlsSocket = tls.connect(tlsOpts); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); +} //////////////////////////////////////////////////// /// Http tests : http://nodejs.org/api/http.html /// diff --git a/node/node-tests.ts b/node/node-tests.ts index e0600d936d..06fb4a9bf7 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -544,21 +544,23 @@ namespace crypto_tests { } } -//////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; +namespace tls_tests { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + var blah = ctx.context; -var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 -}; -var tlsSocket = tls.connect(connOpts); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); +} //////////////////////////////////////////////////// /// Http tests : http://nodejs.org/api/http.html /// From 3e403832f65f64c1ad1b2e29e4e520838519e14b Mon Sep 17 00:00:00 2001 From: Tommy Frazier Date: Mon, 19 Sep 2016 02:10:41 -0400 Subject: [PATCH 055/154] Add httpsServerOptions to ServerOptions interface (#11155) --- restify/restify.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/restify/restify.d.ts b/restify/restify.d.ts index d8e1a37576..65b3f44d47 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -452,6 +452,7 @@ declare module "restify" { responseTimeFormatter ?: (durationInMilliseconds: number) => any; handleUpgrades ?: boolean; router ?: Router; + httpsServerOptions?: any; } interface ClientOptions { From 5e55876028163634704f9f73db4fce2314e02a7d Mon Sep 17 00:00:00 2001 From: Constantin Date: Mon, 19 Sep 2016 08:11:16 +0200 Subject: [PATCH 056/154] webix - added fail to Promise (#11250) --- webix/webix.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webix/webix.d.ts b/webix/webix.d.ts index 9c516654a1..7931ef83d9 100644 --- a/webix/webix.d.ts +++ b/webix/webix.d.ts @@ -9,6 +9,7 @@ type WebixTemplate = (...args: any[])=>string; type WebixCallback = (...args: any[])=>any; interface PromisedData { then(handler:(data:any)=>any):PromisedData; + fail(handler:(error:any)=>any):PromisedData; } function ajax():webix._ajax; @@ -8620,4 +8621,4 @@ interface window extends webix.ui.baseview{ }} -declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; \ No newline at end of file +declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; From 863fdd02c68c82696163f06d8d5b8ce40a10f64d Mon Sep 17 00:00:00 2001 From: Natan Vivo Date: Mon, 19 Sep 2016 03:13:38 -0300 Subject: [PATCH 057/154] Added component option to angular ui bootstrap modal settings. (#11249) --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index dd129d141d..1d0e28b859 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -329,6 +329,12 @@ declare namespace angular.ui.bootstrap { * @default false */ bindToController?: boolean; + + /** + * A string reference to the component to be rendered that is registered with Angular's compiler. + * If using a directive, the directive must have restrict: 'E' and a template or templateUrl set. + */ + component?: string; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes From e69548d34035dbb8dfb11162c6e1b2df0a894a79 Mon Sep 17 00:00:00 2001 From: Martin D Date: Mon, 19 Sep 2016 02:15:00 -0400 Subject: [PATCH 058/154] Fixed arguments for tooltips value formatting (#11253) * Update c3.d.ts Fixed arguments for tooltips value formatting * Update c3.d.ts --- c3/c3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c3/c3.d.ts b/c3/c3.d.ts index 2838ba2675..e815b44391 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -681,7 +681,7 @@ declare namespace c3 { * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. * If undefined returned, the row of that value will be skipped. */ - value?: (name: string, ratio: number, id: string, index: number) => string; + value?: (value: any, ratio: number, id: string, index: number) => string; }; /** * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. From 83adc941d134189c3a55afb73e940ce70308b35b Mon Sep 17 00:00:00 2001 From: Zipeng WU Date: Mon, 19 Sep 2016 08:15:16 +0200 Subject: [PATCH 059/154] Support syncBrushing option on Focus component (#11204) --- nvd3/nvd3.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/nvd3/nvd3.d.ts b/nvd3/nvd3.d.ts index 769d900399..75e6693bdc 100644 --- a/nvd3/nvd3.d.ts +++ b/nvd3/nvd3.d.ts @@ -159,6 +159,8 @@ declare namespace nv { interpolate(value: string): this; rightAlignYAxis(): boolean; rightAlignYAxis(value: boolean): this; + syncBrushing(): boolean; + syncBrushing(value: boolean): this; } interface Nvd3Axis extends d3.svg.Axis { From c0ce167c104f2224111c87fb81c8be5c530916ba Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:15:35 -0400 Subject: [PATCH 060/154] Improve polylabel ES6 import syntax (#11260) Using `import * as polylabel from 'polylabel'` is now valid in Typescript vs. require('polylabel'). --- polylabel/polylabel-tests.ts | 12 +++++------- polylabel/polylabel.d.ts | 5 +++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/polylabel/polylabel-tests.ts b/polylabel/polylabel-tests.ts index 9e23d20d38..e428dbfdb3 100644 --- a/polylabel/polylabel-tests.ts +++ b/polylabel/polylabel-tests.ts @@ -1,10 +1,8 @@ /// -/// -import polylabel = require('polylabel'); +import * as polylabel from 'polylabel'; const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]] -let p: number[] -p = polylabel(polygon) -p = polylabel(polygon, 1.0) -p = polylabel(polygon, 1.0, true) -p = polylabel(polygon, 1.0, false) +polylabel(polygon) +polylabel(polygon, 1.0) +polylabel(polygon, 1.0, true) +polylabel(polygon, 1.0, false) diff --git a/polylabel/polylabel.d.ts b/polylabel/polylabel.d.ts index 21f50d1b41..1fe6aec3df 100644 --- a/polylabel/polylabel.d.ts +++ b/polylabel/polylabel.d.ts @@ -15,7 +15,7 @@ * - guarantees finding global optimum within the given precision * - is many times faster (10-40x) */ -declare module 'polylabel' { +declare module "polylabel" { /** * Polylabel returns the pole of inaccessibility coordinate in [x, y] format. * @@ -28,6 +28,7 @@ declare module 'polylabel' { * @example * var p = polylabel(polygon, 1.0); */ - function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[]; + function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[]; + namespace polylabel {} export = polylabel; } From 50155318b25a75908cb1427ac8b1ab7a9108949c Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Mon, 19 Sep 2016 01:16:16 -0500 Subject: [PATCH 061/154] fix function signatures (#11261) Documentation: https://github.com/mgonto/restangular#restangular-methods According to the documentation and source code, `all` and `allUrl` return collections, not elements. Additionally, the `post` signature without `subElement` is only available on collections, not elements. --- restangular/restangular.d.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 8daa5c0b08..b0ae6b7ca5 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -84,8 +84,8 @@ declare namespace restangular { one(route: string, id?: number): IElement; one(route: string, id?: string): IElement; oneUrl(route: string, url: string): IElement; - all(route: string): IElement; - allUrl(route: string, url: string): IElement; + all(route: string): ICollection; + allUrl(route: string, url: string): ICollection; copy(fromElement: any): IElement; withConfig(configurer: (RestangularProvider: IProvider) => any): IService; restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; @@ -104,8 +104,6 @@ declare namespace restangular { put(queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: T, queryParams?: any, headers?: any): IPromise; - post(elementToPost: any, queryParams?: any, headers?: any): IPromise; - post(elementToPost: T, queryParams?: any, headers?: any): IPromise; remove(queryParams?: any, headers?: any): IPromise; head(queryParams?: any, headers?: any): IPromise; trace(queryParams?: any, headers?: any): IPromise; From 609f1f78e8e830c46cb3ac6876102c62d274821f Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:17:07 -0400 Subject: [PATCH 062/154] Implement concaveman definition (#11262) * Implement concaveman definition Author of concaveman module @mourner * remove console log --- concaveman/concaveman-tests.ts | 5 +++++ concaveman/concaveman.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 concaveman/concaveman-tests.ts create mode 100644 concaveman/concaveman.d.ts diff --git a/concaveman/concaveman-tests.ts b/concaveman/concaveman-tests.ts new file mode 100644 index 0000000000..ddb1e6d125 --- /dev/null +++ b/concaveman/concaveman-tests.ts @@ -0,0 +1,5 @@ +/// +import * as concaveman from 'concaveman'; + +var points = [[10, 20], [30, 12.5]]; +var polygon = concaveman(points); \ No newline at end of file diff --git a/concaveman/concaveman.d.ts b/concaveman/concaveman.d.ts new file mode 100644 index 0000000000..a5b55c8fa3 --- /dev/null +++ b/concaveman/concaveman.d.ts @@ -0,0 +1,24 @@ +// Type definitions for concaveman 1.1.0 +// Project: https://github.com/mapbox/concaveman +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "concaveman" { + /** + * A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set). + * + * @name concaveman + * @param {Array>} points is an array of [x, y] points. + * @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes. + * @param {number} [lengthThreshold=0] when a segment length is under this threshold, it stops being considered for further detalization. Higher values result in simpler shapes. + * @return {Array>} + * @example + * var points = [[10, 20], [30, 12.5], ...]; + * var polygon = concaveman(points); + * + * //=hull + */ + function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][]; + namespace concaveman {} + export = concaveman; +} From 8a8a1396214462baab5b04c498d3b2d869d4c5ed Mon Sep 17 00:00:00 2001 From: Alexander Kalitenya Date: Mon, 19 Sep 2016 11:17:38 +0500 Subject: [PATCH 063/154] Update auth0.lock.d.ts (#11199) --- auth0.lock/auth0.lock.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 43d842aecc..2d74f6e6a5 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -92,7 +92,7 @@ interface Auth0LockConstructorOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; language?: string; languageDictionary?: any; - loginAfterSignup?: boolean; + loginAfterSignUp?: boolean; mustAcceptTerms?: boolean; popupOptions?: Auth0LockPopupOptions; prefill?: { email?: string, username?: string}; From 18d656dda34aae2e331ab2c462c6aa328fbd387e Mon Sep 17 00:00:00 2001 From: ersimont Date: Mon, 19 Sep 2016 02:19:25 -0400 Subject: [PATCH 064/154] Update angular-ui-bootstrap.d.ts (#11263) Add `component` option for modals --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 1d0e28b859..71ef8b7363 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -406,6 +406,17 @@ declare namespace angular.ui.bootstrap { * @default 'body' */ appendTo?: angular.IAugmentedJQuery; + + /** + * A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set. + * + * It supports these bindings: + * - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}` + * - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}` + * - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`. + * - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details. + */ + component?: string; } interface IModalStackService { From b0a9f0e1dbf998308a54f7738b8779f83f00c3fc Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Mon, 19 Sep 2016 08:24:20 +0200 Subject: [PATCH 065/154] Add totalFrames and duration properties to MovieClip (#11270) Official documentation for those properties: - http://www.createjs.com/docs/easeljs/classes/MovieClip.html#property_totalFrames - http://www.createjs.com/docs/easeljs/classes/MovieClip.html#property_duration --- easeljs/easeljs.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index 3ddeabdef9..ab8cd5a0e1 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -650,6 +650,7 @@ declare namespace createjs { autoReset: boolean; static buildDate: string; currentFrame: number; + totalFrames: number; currentLabel: string; frameBounds: Rectangle[]; framerate: number; @@ -662,6 +663,7 @@ declare namespace createjs { startPosition: number; static SYNCHED: string; timeline: Timeline; + duration: number; static version: string; // methods From 48649b87187b5ff3448d291c847a35da65d12d93 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:29:20 +0800 Subject: [PATCH 066/154] [node] Add events and exitedAfterDisconnect in cluster.work (#11275) * Add events for cluster.worker * Add exitedAfterDisconnect for cluster.Worker --- node/node.d.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 81b13e4e1d..54e826301a 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -778,6 +778,56 @@ declare module "cluster" { disconnect(): void; isConnected(): boolean; isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; } export interface Cluster extends events.EventEmitter { From 28d94377786d6da325b76614aa4c1849dc05703e Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:30:32 +0800 Subject: [PATCH 067/154] Add events for fs (#11277) --- node/node.d.ts | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 54e826301a..888da5cec4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1788,16 +1788,92 @@ declare module "fs" { interface FSWatcher extends events.EventEmitter { close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; } export interface ReadStream extends stream.Readable { close(): void; destroy(): void; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } + export interface WriteStream extends stream.Writable { close(): void; bytesWritten: number; path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } /** From 93d269d6da3a675d49648330b412a6c7b6981c89 Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Sun, 18 Sep 2016 23:49:21 -0700 Subject: [PATCH 068/154] added prop options and func timeFormatter (#11256) added property `options`, which can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L270). Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme. added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L795) --- smoothie/smoothie.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index 98f205f598..c396261c52 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -141,6 +141,8 @@ declare module "smoothie" */ export class SmoothieChart { + options: IChartOptions; + constructor(chartOptions?: IChartOptions); /** @@ -188,5 +190,7 @@ declare module "smoothie" updateValueRange(): void; render(canvas?: HTMLCanvasElement, time?: number): void; + + static timeFormatter(date: Date): string; } } From 80e5c9b45b7ddd6442bcabbebf418fa1a658307b Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:50:52 -0400 Subject: [PATCH 069/154] Define Turf 3.5.2 definition (#11123) * Define Turf 3.5.2 definition Update all methods with newest JSDocs & tests based on the latest TurfJS library. AGGREGATION - [x] collect MEASUREMENT - [ ] along - [ ] area - [ ] bboxPolygon - [ ] bearing - [ ] center - [ ] centroid - [ ] destination - [ ] distance - [ ] envelope - [ ] lineDistance - [ ] midpoint - [ ] pointOnSurface - [ ] square TRANSFORMATION - [ ] bezier - [ ] buffer - [ ] concave - [ ] convex - [ ] difference - [ ] intersect - [ ] simplify - [ ] union MISC - [ ] combine - [ ] explode - [ ] flip - [ ] kinks - [ ] lineSlice - [ ] pointOnLine HELPER - [x] featureCollection - [x] feature - [x] lineString - [x] multiLineString - [x] point - [x] multiPoint - [x] polygon - [x] multiPolygon - [x] geometryCollection DATA - [x] random - [x] sample INTERPOLATION - [ ] isolines - [ ] planepoint - [ ] tin JOINS - [ ] inside - [ ] tag GRIDS - [ ] hexGrid - [ ] pointGrid - [ ] squareGrid - [ ] triangleGrid - [ ] within CLASSIFICATION - [ ] nearest META - [ ] propEach - [ ] coordEach - [ ] coordReduce - [ ] featureEach - [ ] getCoord ASSERTIONS - [ ] featureOf - [ ] collectionOf - [ ] bbox - [ ] circle - [ ] geojsonType - [ ] propReduce - [ ] coordAll - [ ] tesselate * Added Turf Grids functions - Added more variables to data initialisation. - Remove excess feature points. - Add URL in `@name` in function JSDocs GRIDS - [x] hexGrid - [x] pointGrid - [x] squareGrid - [x] triangleGrid * Use the latest Turf import - Added in test case how to import individal functions npm install in Node.js ``` npm install @turf/turf ``` https://github.com/Turfjs/turf * Change Turf functions into interfaces * Added Turf typeof units `units` is an optional parameter for all Turf functions with the following options `'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres'` * Update Turf `inside` & `tag` Add JSDocs & validate both methods * Add imports to Turf submodules * Add Author to Turf @vvakame followed the same syntax as Lodash * Simplify Turf `intersect` interface Turf only officially supports `poly,poly`, all other geometry input/outputs are valid, however can't control the outputs. https://github.com/Turfjs/turf/pull/479 * Comment Turf export default module Next release of Turf will have this implemented * Remove default export turf Was meant to be a comment instead, removed it for now to be safe, it will become available next release * Added Turf.bbox function --- turf/turf-2.0-tests.ts | 522 +++++++++++++++++ turf/turf-2.0.d.ts | 580 +++++++++++++++++++ turf/turf-tests.ts | 512 +++++++++-------- turf/turf.d.ts | 1203 ++++++++++++++++++++++++++++++---------- 4 files changed, 2265 insertions(+), 552 deletions(-) create mode 100644 turf/turf-2.0-tests.ts create mode 100644 turf/turf-2.0.d.ts diff --git a/turf/turf-2.0-tests.ts b/turf/turf-2.0-tests.ts new file mode 100644 index 0000000000..45d9dbcc42 --- /dev/null +++ b/turf/turf-2.0-tests.ts @@ -0,0 +1,522 @@ +/// + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// + +var point1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.343, 39.984] + } +}; + +var point2: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.534, 39.123] + } +}; + +var line: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-77.031669, 38.878605], + [-77.029609, 38.881946], + [-77.020339, 38.884084], + [-77.025661, 38.885821], + [-77.021884, 38.889563], + [-77.019824, 38.892368] + ] + } +}; + +var polygons: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-67.031021, 10.458102], + [-67.031021, 10.53372], + [-66.929397, 10.53372], + [-66.929397, 10.458102], + [-67.031021, 10.458102] + ]] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-66.919784, 10.397325], + [-66.919784, 10.513467], + [-66.805114, 10.513467], + [-66.805114, 10.397325], + [-66.919784, 10.397325] + ]] + } + } + ] +}; + +var polygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [105.818939,21.004714], + [105.818939,21.061754], + [105.890007,21.061754], + [105.890007,21.004714], + [105.818939,21.004714] + ]] + } +}; + +var polygon2: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "fill": "#00f" + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-122.520217, 45.535693], + [-122.64038, 45.553967], + [-122.720031, 45.526554], + [-122.669906, 45.507309], + [-122.723464, 45.446643], + [-122.532577, 45.408574], + [-122.487258, 45.477466], + [-122.520217, 45.535693] + ]] + } +} + +var features: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.522259, 35.4691] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.502754, 35.463455] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508269, 35.463245] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.516809, 35.465779] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.515372, 35.467072] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.509363, 35.463053] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.511123, 35.466601] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.518547, 35.469327] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.519706, 35.469659] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.517839, 35.466998] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508678, 35.464942] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.514914, 35.463453] + } + } + ] +}; + +var triangle: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "a": 11, + "b": 122, + "c": 44 + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-75.1221, 39.57], + [-75.58, 39.18], + [-75.97, 39.86], + [-75.1221, 39.57] + ]] + } +}; + +var aggregations = [ + { + aggregation: 'sum', + inField: 'population', + outField: 'pop_sum' + }, + { + aggregation: 'average', + inField: 'population', + outField: 'pop_avg' + }, + { + aggregation: 'median', + inField: 'population', + outField: 'pop_median' + }, + { + aggregation: 'min', + inField: 'population', + outField: 'pop_min' + }, + { + aggregation: 'max', + inField: 'population', + outField: 'pop_max' + }, + { + aggregation: 'deviation', + inField: 'population', + outField: 'pop_deviation' + }, + { + aggregation: 'variance', + inField: 'population', + outField: 'pop_variance' + }, + { + aggregation: 'count', + inField: '', + outField: 'point_count' + } +]; + +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// + +// -- Test aggregate -- +var aggregated = turf.aggregate(polygons, points, aggregations); + +// -- Test average -- +var averaged = turf.average(polygons, points, 'population', 'pop_avg'); + +// -- Test count -- +var counted = turf.count(polygons, points, 'pt_count'); + +// -- Test deviation -- +var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); + +// -- Test max -- +var aggregated = turf.max(polygons, points, 'population', 'max'); + +// -- Test median -- +var medians = turf.median(polygons, points, 'population', 'median'); + +// -- Test min -- +var minimums = turf.min(polygons, points, 'population', 'min'); + +// -- Test sum -- +var summed = turf.sum(polygons, points, 'population', 'sum'); + +// -- Test variance -- +var varianced = turf.variance(polygons, points, 'population', 'variance'); + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// + +// -- Test along -- +var along = turf.along(line, 1, 'miles'); + +// -- Test area -- +var area = turf.area(polygons); + +// -- Test bboxPolygon -- +var bbox = [0, 0, 10, 10]; +var poly = turf.bboxPolygon(bbox); + +// -- Test bearing -- +var bearing = turf.bearing(point1, point2); + +// -- Test center +var centerPt = turf.center(features); + +// -- Test centroid -- +var centroidPt = turf.centroid(polygon1); + +// -- Test destination -- +var distance = 50; +var bearing = 90; +var units = 'miles'; +var destination = turf.destination(point1, distance, bearing, units); + +// -- Test distance -- +var units = "miles"; +var distance = turf.distance(point1, point2, units); + +// -- Test envelope -- +var enveloped = turf.envelope(polygons); + +// -- Test extent -- +var bbox = turf.extent(polygons); + +// -- Test lineDistance +var length = turf.lineDistance(line, 'miles'); + +// -- Test midpoint -- +var midpointed = turf.midpoint(point1, point2); + +// -- Test pointOnSurface -- +var pointOnPolygon = turf.pointOnSurface(polygon1); + +// -- Test size -- +var resized = turf.size(bbox, 2); + +// -- Test square -- +var squared = turf.square(bbox); + +/////////////////////////////////////////// +// Tests Transformation +/////////////////////////////////////////// + +// -- Test bezier -- +var curved = turf.bezier(line); + +// -- Test buffer -- +var buffered = turf.buffer(point1, 500, units); + +// -- Test concave -- +var hull = turf.concave(features, 1, 'miles'); + +// -- Test convex -- +var hull = turf.convex(features); + +// -- Test difference -- +var differenced = turf.difference(polygon1, polygon2); + +// -- Test intersect -- +var intersection = turf.intersect(polygon1, polygon2); + +// -- Test merge -- +var merged = turf.merge(polygons); + +// -- Test simplify -- +var tolerance = 0.01; +var simplified = turf.simplify(polygon1, tolerance, false); + +// -- Test union -- +var union = turf.union(polygon1, polygon2); + +/////////////////////////////////////////// +// Tests Misc +/////////////////////////////////////////// + +// -- Test combine -- +var combined = turf.combine(features); + +// -- Test explode -- +var points = turf.explode(polygon1); + +// -- Test flip -- +var flipedPoint = turf.flip(point1); + +// -- Test kinks -- +var kinks = turf.kinks(polygon1); + +// -- Test lineSlice -- +var sliced = turf.lineSlice(point1, point2, line); + +// -- Test pointOnLine -- +var snapped = turf.pointOnLine(line, point1); + +/////////////////////////////////////////// +// Tests Helper +/////////////////////////////////////////// + +// -- Test featurecollection -- +var fc = turf.featurecollection([point1, point2]); + +// -- Test linestring -- +var linestring1 = turf.linestring([ + [-21.964416, 64.148203], + [-21.956176, 64.141316], + [-21.93901, 64.135924], + [-21.927337, 64.136673] +]); +var linestring2 = turf.linestring([ + [-21.929054, 64.127985], + [-21.912918, 64.134726], + [-21.916007, 64.141016], + [-21.930084, 64.14446] +], {name: 'line 1', distance: 145}); + +// -- Test point -- +var pt1 = turf.point([-75.343, 39.984]); +var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); + +// -- Test polygon -- +var polygon = turf.polygon([[ + [-2.275543, 53.464547], + [-2.275543, 53.489271], + [-2.215118, 53.489271], + [-2.215118, 53.464547], + [-2.275543, 53.464547] +]], { name: 'poly1', population: 400}); + +/////////////////////////////////////////// +// Tests Data +/////////////////////////////////////////// + +// -- Test filter -- +var key = "species"; +var value = "oak"; +var filtered = turf.filter(features, key, value); + +// -- Test random -- +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60] +}); + +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60], + num_vertices: 2, + max_radial_length: 10 +}); + +// -- Test remove -- +var filtered = turf.remove(points, 'marker-color', '#00f'); + +// -- Test sample -- +var randomPoints = turf.random('points', 1000); +var sample = turf.sample(points, 10); + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test hexGrid -- +var cellWidth = 50; +var hexgrid = turf.hexGrid(bbox, cellWidth, units); + +// -- Test isolines -- +var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +var isolined = turf.isolines(points, 'z', 15, breaks); + +// -- Test planepoint -- +var zValue = turf.planepoint(point1, triangle); + +// -- Test pointGrid -- +var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; +var cellWidth = 3; +var grid = turf.pointGrid(extent, cellWidth, units); + +// -- Test squareGrid -- +var squareGrid = turf.squareGrid(extent, cellWidth, units); + +// -- Test tin -- +var tin = turf.tin(points, 'z'); + +// -- Test triangleGrid -- +var triangleGrid = turf.triangleGrid(extent, cellWidth, units); + +/////////////////////////////////////////// +// Tests Joins +/////////////////////////////////////////// + +// -- Test inside -- +var isInside1 = turf.inside(point1, polygon); + +// -- Test tag -- +var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); + +// -- Test within -- +var ptsWithin = turf.within(points, polygons); + +/////////////////////////////////////////// +// Tests Classification +/////////////////////////////////////////// + +// -- Test jenks -- +var breaks = turf.jenks(points, 'population', 3); + +// -- Test nearest -- +var nearest = turf.nearest(point1, points); + +// -- Test quantile -- +var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); + +// -- Test reclass -- +var translations = [ + [0, 200, "small"], + [200, 400, "medium"], + [400, 600, "large"] +]; +var reclassed = turf.reclass(points, 'population', 'size', translations); diff --git a/turf/turf-2.0.d.ts b/turf/turf-2.0.d.ts new file mode 100644 index 0000000000..647df93398 --- /dev/null +++ b/turf/turf-2.0.d.ts @@ -0,0 +1,580 @@ +// Type definitions for Turf 2.0 +// Project: http://turfjs.org/ +// Definitions by: Guillaume Croteau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module turf { + ////////////////////////////////////////////////////// + // Aggregation + ////////////////////////////////////////////////////// + + /** + * Calculates a series of aggregations for a set of points within a set of polygons. + * Sum, average, count, min, max, and deviation are supported. + * @param polygons Polygons with values on which to aggregate + * @param points Points to be aggregated + * @param aggregations An array of aggregation objects + * @returns Polygons with properties listed based on outField values in aggregations + */ + function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; + + /** + * Calculates the average value of a field for a set of points within a set of polygons. + * @param polygons Polygons with values on which to average + * @param points Points from which to calculate the average + * @param field The field in the points features from which to pull values to average + * @param outField The field in polygons to put results of the averages + * @returns Polygons with the value of outField set to the calculated averages + */ + function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param countField A field to append to the attributes of the Polygon features representing Point counts + * @returns Polygons with countField appended + */ + function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the standard deviation value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in points from which to aggregate + * @param outField The field to append to polygons representing deviation + * @returns Polygons with appended field representing deviation + */ + function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the maximum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the median value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the minimum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the sum of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the variance value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Measurement + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a point at a specified distance along the line. + * @param line Input line + * @param distance Distance along the line + * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' + * @returns Point along the line + */ + function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + + /** + * Takes one or more features and returns their area in square meters. + * @param input Input features + * @returns Area in square meters + */ + function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a bbox and returns an equivalent polygon. + * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] + * @returns A Polygon representation of the bounding box + */ + function bboxPolygon(bbox: Array): GeoJSON.Feature; + + /** + * Takes two points and finds the geographic bearing between them. + * @param start Starting Point + * @param end Ending point + * @returns Bearing in decimal degrees + */ + function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + + /** + * Takes a FeatureCollection and returns the absolute center point of all features. + * @param features Input features + * @returns A Point feature at the absolute center point of all input features + */ + function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. + * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons. + * @param features Input features + * @returns The centroid of the input features + */ + function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * This uses the Haversine formula to account for global curvature. + * @param start Starting point + * @param distance Distance from the starting point + * @param bearing Ranging from -180 and 180 + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Destination point + */ + function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + + /** + * Calculates the distance between two points in degress, radians, miles, or kilometers. + * This uses the Haversine formula to account for global curvature. + * @param from Origin point + * @param to Destination point + * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Distance between the two points + */ + function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + + /** + * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. + * @param fc Input features + * @returns A rectangular Polygon feature that encompasses all vertices + */ + function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a set of features, calculates the extent of all input features, and returns a bounding box. + * @param input Input features + * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) + */ + function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + + /** + * Takes a line and measures its length in the specified units. + * @param line Line to measure + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Length of the input line + */ + function lineDistance(line: GeoJSON.Feature, units: string): number; + + /** + * Takes two points and returns a point midway between them. + * @param pt1 First point + * @param pt2 Second point + * @returns A point midway between pt1 and pt2 + */ + function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. + * Given a LineString, the point will be along the string. Given a Point, the point will the same as the input. + * @param input Any feature or set of features + * @returns A point on the surface of input + */ + function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. + * @param bbox A bounding box + * @param factor The ratio of the new bbox to the input bbox + * @returns The resized bbox + */ + function size(bbox: Array, factor: number): Array; + + /** + * Takes a bounding box and calculates the minimum square bounding box that would contain the input. + * @param bbox A bounding box + * @returns A square surrounding bbox + */ + function square(bbox: Array): Array; + + ////////////////////////////////////////////////////// + // Transformation + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a curved version by applying a Bezier spline algorithm. + * The bezier spline implementation is by Leszek Rybicki. + * @param line Input LineString + * @param [resolution=10000] Time in milliseconds between points + * @param [sharpness=0.85] A measure of how curvy the path should be between splines + * @returns Curved line + */ + function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + + /** + * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. + * @param feature Input to be buffered + * @param distance Distance to draw the buffer + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Buffered features + */ + function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + + /** + * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. + * @param points Input points + * @param maxEdge The size of an edge necessary for part of the hull to become concave (in miles) + * @param units Used for maxEdge distance (miles or kilometers) + * @returns A concave hull + */ + function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + + /** + * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. + * @param input Input points + * @returns A convex hull + */ + function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Finds the difference between two polygons by clipping the second polygon from the first. + * @param poly1 Input Polygon feaure + * @param poly2 Polygon feature to difference from poly1 + * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 + */ + function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes two polygons and finds their intersection. + * If they share a border, returns the border; if they don't intersect, returns undefined. + * @param poly1 The first polygon + * @param poly2 The second polygon + * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; + * if poly1 and poly2 do not overlap, returns undefined; + * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared + */ + function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; + + /** + * Takes a set of polygons and returns a single merged polygon feature. + * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. + * @param fc Input polygons + * @returns Merged polygon or multipolygon + */ + function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a LineString or Polygon and returns a simplified version. + * Internally uses simplify-js to perform simplification. + * @param feature Feature to be simplified + * @param tolerance Simplification tolerance + * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm + * @returns A simplified feature + */ + function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + + /** + * Takes two polygons and returns a combined polygon. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * @param poly1 Input polygon + * @param poly2 Another input polygon + * @returns A combined Polygon or MultiPolygon feature + */ + function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Misc + ////////////////////////////////////////////////////// + + /** + * Combines a FeatureCollection of Point, LineString, or Polygon features into MultiPoint, MultiLineString, or MultiPolygon features. + * @param fc A FeatureCollection of any type + * @returns A FeatureCollection of corresponding type to input + */ + function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes a feature or set of features and returns all positions as points. + * @param input Input features + * @returns Points representing the exploded input features + */ + function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes input features and flips all of their coordinates from [x, y] to [y, x]. + * @param input Input features + * @returns A feature or set of features of the same type as input with flipped coordinates + */ + function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + + /** + * Takes a polygon and returns points at all self-intersections. + * @param polygon Input polygon + * @returns Self-intersections + */ + function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + + /** + * Takes a line, a start Point, and a stop point and returns the line in between those points. + * @param point1 Starting point + * @param point2 Stopping point + * @param line Line to slice + * @returns Sliced line + */ + function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a Point and a LineString and calculates the closest Point on the LineString. + * @param line Line to snap to + * @param point Point to snap from + * @returns Closest point on the line to point + */ + function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Helper + ////////////////////////////////////////////////////// + + /** + * Takes one or more Features and creates a FeatureCollection. + * @param features Input features + * @returns A FeatureCollection of input features + */ + function featurecollection(features: Array>): GeoJSON.FeatureCollection; + + /** + * Creates a LineString based on a coordinate array. Properties can be added optionally. + * @param coordinates An array of Positions + * @param [properties] An Object of key-value pairs to add as properties + * @returns A LineString feature + */ + function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new Point feature. + * @param coordinates Longitude, latitude position (each in decimal degrees) + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Point feature + */ + function point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. + * @param rings An array of LinearRings + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Polygon feature + */ + function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Data + ////////////////////////////////////////////////////// + + /** + * Takes a FeatureCollection and filters it by a given property and value. + * @param features Input features + * @param key The property on which to filter + * @param value The value of that property on which to filter + * @returns A filtered collection with only features that match input key and value + */ + function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + + /** + * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. + * @param [type='point'] Type of features desired: 'points' or 'polygons' + * @param [count=1] How many geometries should be generated. + * @param [options] Options relevant to the feature desired. Can include: + * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. + * - The number of vertices added to polygon features. Default is 10; + * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. + * @returns Generated random features + */ + function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. + * @param features Set of input features + * @param property The property to remove + * @param value The value to remove + * @returns The resulting FeatureCollection without features that match the property-value pair + */ + function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. + * @param features Set of input features + * @param n Number of features to select + * @returns A FeatureCollection with n features + */ + function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Interpolation + ////////////////////////////////////////////////////// + + /** + * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. + * @param bbox Bounding box in [minX, minY, maxX, maxY] order + * @param cellWidth Width of cell in specified units + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns A hexagonal grid + */ + function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes points with z-values and an array of value breaks and generates isolines. + * @param points Input points + * @param z The property name in points from which z-values will be pulled + * @param resolution Resolution of the underlying grid + * @param breaks Where to draw contours + * @returns Isolines + */ + function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + + /** + * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. + * The Polygon needs to have properties a, b, and c that define the values at its three corners. + * @param interpolatedPoint The Point for which a z-value will be calculated + * @param triangle A Polygon feature with three vertices + * @returns The z-value for interpolatedPoint + */ + function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; + + /** + * Takes a bounding box and a cell depth and returns a set of points in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth The distance across each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of points + */ + function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of polygons + */ + function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. + * These are often used for developing elevation contour maps or stepped heat visualizations. + * This triangulates the points, as well as adds properties called a, b, and c representing the value of the given propertyName at each of the points that represent the corners of the triangle. + * @param points Input points + * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. + * @returns TIN output + */ + function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of triangles + */ + function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Joins + ////////////////////////////////////////////////////// + + /** + * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. + * The polygon can be convex or concave. The function accounts for holes. + * @param point Input point + * @param polygon Input polygon or multipolygon + * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon + */ + function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + + /** + * Takes a set of points and a set of polygons and performs a spatial join. + * @param points Input points + * @param polygons Input polygons + * @param polyId Property in polygons to add to joined Point features + * @param containingPolyId Property in points in which to store joined property from polygons + * @returns Points with containingPolyId property containing values from polyId + */ + function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and returns the points that fall within the polygons. + * @param points Input points + * @param polygons Input polygons + * @returns Points that land within at least one polygon + */ + function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Classification + ////////////////////////////////////////////////////// + + /** + * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. + * @param input Input features + * @param field The property in input on which to calculate Jenks natural breaks + * @param numberOfBreaks Number of classes in which to group the data + * @returns The break number for each class plus the minimum and maximum values + */ + function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; + + /** + * Takes a reference point and a set of points and returns the point from the set closest to the reference. + * @param point The reference point + * @param against Input point set + * @returns The closest point in the set to the reference point + */ + function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. + * @param input Set of features + * @param field The property in input from which to retrieve quantile values + * @param percentiles An Array of percentiles on which to calculate quantile values + * @returns An array of the break values + */ + function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; + + /** + * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. + * @param input Set of input features + * @param inField The field to translate + * @param outField The field in which to store translated results + * @param translations An array of translations + * @returns A FeatureCollection with identical geometries to input but with outField populated. + */ + function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; +} + +declare module 'turf' { + export= turf; +} diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index e671035892..31462adc51 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -1,28 +1,114 @@ /// +import * as turf from '@turf/turf' +// AGGREGATION +import * as collect from '@turf/collect' +// MEASUREMENT +import * as along from '@turf/along' +import * as area from '@turf/area' +import * as bboxPolygon from '@turf/bbox-polygon' +import * as bearing from '@turf/bearing' +import * as center from '@turf/center' +import * as centroid from '@turf/centroid' +import * as destination from '@turf/destination' +import * as envelope from '@turf/envelope' +import * as lineDistance from '@turf/line-distance' +import * as midpoint from '@turf/midpoint' +import * as pointOnSurce from '@turf/point-on-surface' +import * as square from '@turf/square' +// TRANSFORMATION +import * as bezier from '@turf/bezier' +import * as buffer from '@turf/buffer' +import * as concave from '@turf/concave' +import * as convex from '@turf/convex' +import * as difference from '@turf/difference' +import * as intersect from '@turf/intersect' +import * as simplify from '@turf/simplify' +import * as union from '@turf/union' +// MISC +import * as combine from '@turf/combine' +import * as explode from '@turf/explode' +import * as flip from '@turf/flip' +import * as kinks from '@turf/kinks' +import * as lineSlice from '@turf/line-slice' +import * as pointOnLine from '@turf/point-on-line' +// HELPER +import { + featureCollection, + feature, + lineString, + multiLineString, + point, + multiPoint, + polygon, + multiPolygon, + geometryCollection } from '@turf/helpers' +// DATA +import * as random from '@turf/random' +import * as sample from '@turf/sample' +// INTERPOLATION +import * as isolines from '@turf/isolines' +import * as planepoint from '@turf/planepoint' +import * as tin from '@turf/tin' +// JOINS +import * as inside from '@turf/inside' +import * as tag from '@turf/tag' +import * as within from '@turf/within' +// GRIDS +import * as hexGrid from '@turf/hex-grid' +import * as pointGrid from '@turf/point-grid' +import * as squareGrid from '@turf/square-grid' +import * as triangleGrid from '@turf/triangle-grid' +// CLASSIFICATION +import * as nearest from '@turf/nearest' +// // META +// import * as propEach from '@turf/propEach' +// import * as coordEach from '@turf/coordEach' +// import * as coordReduce from '@turf/coordReduce' +// import * as featureEach from '@turf/featureEach' +// import * as getCoord from '@turf/getCoord' +// // ASSERTIONS +// import * as featureOf from '@turf/featureOf' +// import * as collectionOf from '@turf/collectionOf' +import * as bboxAssertions from '@turf/bbox' +// import * as circle from '@turf/circle' +// import * as geojsonType from '@turf/geojsonType' +// import * as propReduce from '@turf/propReduce' +// import * as coordAll from '@turf/coordAll' +// import * as tesselate from '@turf/tesselate' /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// - -var point1: GeoJSON.Feature = { +const bbox = [0, 0, 10, 10] +const properties = {pop: 3000} +const point1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [-75.343, 39.984] } -}; +} -var point2: GeoJSON.Feature = { +const point2: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-75.534, 39.123] - } -}; + "coordinates": [-75.401, 39.884] + } +} -var line: GeoJSON.Feature = { +const multiPoint1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPoint", + "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] + } +} + +const lineString1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -36,9 +122,21 @@ var line: GeoJSON.Feature = { [-77.019824, 38.892368] ] } -}; +} -var polygons: GeoJSON.FeatureCollection = { +const multiLineString1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiLineString", + "coordinates": [ + [ [100.0, 0.0], [101.0, 1.0] ], + [ [102.0, 2.0], [103.0, 3.0] ] + ] + } +} + +const polygons: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -69,9 +167,9 @@ var polygons: GeoJSON.FeatureCollection = { } } ] -}; +} -var polygon1: GeoJSON.Feature = { +const polygon1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -84,13 +182,11 @@ var polygon1: GeoJSON.Feature = { [105.818939,21.004714] ]] } -}; +} -var polygon2: GeoJSON.Feature = { +const polygon2: GeoJSON.Feature = { "type": "Feature", - "properties": { - "fill": "#00f" - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -106,7 +202,20 @@ var polygon2: GeoJSON.Feature = { } } -var features: GeoJSON.FeatureCollection = { +const multiPolygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], + [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + ] + } +} + +const points: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -114,96 +223,50 @@ var features: GeoJSON.FeatureCollection = { "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.522259, 35.4691] + "coordinates": [-63.601226, 44.642643] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.502754, 35.463455] + "coordinates": [-63.591442, 44.651436] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.508269, 35.463245] + "coordinates": [-63.580799, 44.648749] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.516809, 35.465779] + "coordinates": [-63.573589, 44.641788] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.515372, 35.467072] + "coordinates": [-63.587665, 44.64533] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.509363, 35.463053] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.511123, 35.466601] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.518547, 35.469327] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.519706, 35.469659] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.517839, 35.466998] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.508678, 35.464942] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.514914, 35.463453] + "coordinates": [-63.595218, 44.64765] } } ] -}; +} -var triangle: GeoJSON.Feature = { +const triangle: GeoJSON.Feature = { "type": "Feature", - "properties": { - "a": 11, - "b": 122, - "c": 44 - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -213,310 +276,231 @@ var triangle: GeoJSON.Feature = { [-75.1221, 39.57] ]] } -}; - -var aggregations = [ - { - aggregation: 'sum', - inField: 'population', - outField: 'pop_sum' - }, - { - aggregation: 'average', - inField: 'population', - outField: 'pop_avg' - }, - { - aggregation: 'median', - inField: 'population', - outField: 'pop_median' - }, - { - aggregation: 'min', - inField: 'population', - outField: 'pop_min' - }, - { - aggregation: 'max', - inField: 'population', - outField: 'pop_max' - }, - { - aggregation: 'deviation', - inField: 'population', - outField: 'pop_deviation' - }, - { - aggregation: 'variance', - inField: 'population', - outField: 'pop_variance' - }, - { - aggregation: 'count', - inField: '', - outField: 'point_count' - } -]; - -/////////////////////////////////////////// -// Tests Aggregation -/////////////////////////////////////////// - -// -- Test aggregate -- -var aggregated = turf.aggregate(polygons, points, aggregations); - -// -- Test average -- -var averaged = turf.average(polygons, points, 'population', 'pop_avg'); - -// -- Test count -- -var counted = turf.count(polygons, points, 'pt_count'); - -// -- Test deviation -- -var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); - -// -- Test max -- -var aggregated = turf.max(polygons, points, 'population', 'max'); - -// -- Test median -- -var medians = turf.median(polygons, points, 'population', 'median'); - -// -- Test min -- -var minimums = turf.min(polygons, points, 'population', 'min'); - -// -- Test sum -- -var summed = turf.sum(polygons, points, 'population', 'sum'); - -// -- Test variance -- -var varianced = turf.variance(polygons, points, 'population', 'variance'); +} /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// // -- Test along -- -var along = turf.along(line, 1, 'miles'); +turf.along(lineString1, 50) +turf.along(lineString1, 50, 'miles') // -- Test area -- -var area = turf.area(polygons); +turf.area(polygons) // -- Test bboxPolygon -- -var bbox = [0, 0, 10, 10]; -var poly = turf.bboxPolygon(bbox); +turf.bboxPolygon(bbox) // -- Test bearing -- -var bearing = turf.bearing(point1, point2); +turf.bearing(point1, point2) // -- Test center -var centerPt = turf.center(features); +turf.center(points) // -- Test centroid -- -var centroidPt = turf.centroid(polygon1); +turf.centroid(polygon1) // -- Test destination -- -var distance = 50; -var bearing = 90; -var units = 'miles'; -var destination = turf.destination(point1, distance, bearing, units); +turf.destination(point1, 50, 90) +turf.destination(point1, 50, 90, 'miles') // -- Test distance -- -var units = "miles"; -var distance = turf.distance(point1, point2, units); +turf.distance(point1, point2) +turf.distance(point1, point2, 'miles') // -- Test envelope -- -var enveloped = turf.envelope(polygons); - -// -- Test extent -- -var bbox = turf.extent(polygons); +turf.envelope(polygons) // -- Test lineDistance -var length = turf.lineDistance(line, 'miles'); +turf.lineDistance(lineString1) +turf.lineDistance(lineString1, 'miles') // -- Test midpoint -- -var midpointed = turf.midpoint(point1, point2); +turf.midpoint(point1, point2) // -- Test pointOnSurface -- -var pointOnPolygon = turf.pointOnSurface(polygon1); - -// -- Test size -- -var resized = turf.size(bbox, 2); +turf.pointOnSurface(polygon1) // -- Test square -- -var squared = turf.square(bbox); +turf.square(bbox) /////////////////////////////////////////// // Tests Transformation /////////////////////////////////////////// // -- Test bezier -- -var curved = turf.bezier(line); +turf.bezier(lineString1) // -- Test buffer -- -var buffered = turf.buffer(point1, 500, units); +turf.buffer(point1, 50) +turf.buffer(point1, 50, 'miles') // -- Test concave -- -var hull = turf.concave(features, 1, 'miles'); +turf.concave(points, 1, 'miles') // -- Test convex -- -var hull = turf.convex(features); +turf.convex(points) // -- Test difference -- -var differenced = turf.difference(polygon1, polygon2); +turf.difference(polygon1, polygon2) // -- Test intersect -- -var intersection = turf.intersect(polygon1, polygon2); - -// -- Test merge -- -var merged = turf.merge(polygons); +turf.intersect(polygon1, polygon2) +turf.intersect(point1, polygon1) +turf.intersect(point1, point1) +turf.intersect(polygon1, point1) +turf.intersect(polygon1, lineString1) +turf.intersect(lineString1, point1) // -- Test simplify -- -var tolerance = 0.01; -var simplified = turf.simplify(polygon1, tolerance, false); + +turf.simplify(polygon1, 0.01, false) // -- Test union -- -var union = turf.union(polygon1, polygon2); +turf.union(polygon1, polygon2) /////////////////////////////////////////// // Tests Misc /////////////////////////////////////////// // -- Test combine -- -var combined = turf.combine(features); +turf.combine(points) // -- Test explode -- -var points = turf.explode(polygon1); +turf.explode(polygon1) // -- Test flip -- -var flipedPoint = turf.flip(point1); +turf.flip(point1) // -- Test kinks -- -var kinks = turf.kinks(polygon1); +turf.kinks(polygon1) // -- Test lineSlice -- -var sliced = turf.lineSlice(point1, point2, line); +turf.lineSlice(point1, point2, lineString1) // -- Test pointOnLine -- -var snapped = turf.pointOnLine(line, point1); +turf.pointOnLine(lineString1, point1) /////////////////////////////////////////// // Tests Helper /////////////////////////////////////////// // -- Test featurecollection -- -var fc = turf.featurecollection([point1, point2]); +turf.featureCollection([point1, point2]) +turf.featureCollection([point1, polygon1]) +turf.featureCollection([polygon1, polygon2]) +turf.featureCollection([lineString1, polygon1]) +turf.featureCollection([lineString1, point1]) -// -- Test linestring -- -var linestring1 = turf.linestring([ - [-21.964416, 64.148203], - [-21.956176, 64.141316], - [-21.93901, 64.135924], - [-21.927337, 64.136673] -]); -var linestring2 = turf.linestring([ - [-21.929054, 64.127985], - [-21.912918, 64.134726], - [-21.916007, 64.141016], - [-21.930084, 64.14446] -], {name: 'line 1', distance: 145}); +// -- Test feature -- +turf.feature(point1) +turf.feature(polygon1) +turf.feature(lineString1) + +// -- Test lineString -- +turf.lineString(lineString1.geometry.coordinates) +turf.lineString(lineString1.geometry.coordinates, properties) + +// -- Test multiLineString -- +turf.multiLineString(multiLineString1.geometry.coordinates) // -- Test point -- -var pt1 = turf.point([-75.343, 39.984]); -var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); +turf.point(point1.geometry.coordinates) +turf.point(point1.geometry.coordinates, properties) + +// -- Test multiPoint -- +turf.multiPoint(multiPoint1.geometry.coordinates) // -- Test polygon -- -var polygon = turf.polygon([[ - [-2.275543, 53.464547], - [-2.275543, 53.489271], - [-2.215118, 53.489271], - [-2.215118, 53.464547], - [-2.275543, 53.464547] -]], { name: 'poly1', population: 400}); +turf.polygon(polygon1.geometry.coordinates, properties) + +// -- Test multiPolygon -- +turf.multiPolygon(multiPolygon1.geometry.coordinates, properties) + +// -- Test geometryCollection -- +turf.geometryCollection([point1.geometry, lineString1.geometry]); /////////////////////////////////////////// // Tests Data /////////////////////////////////////////// -// -- Test filter -- -var key = "species"; -var value = "oak"; -var filtered = turf.filter(features, key, value); - // -- Test random -- -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60] -}); - -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60], - num_vertices: 2, +turf.random('points', 100) +turf.random('points', 100, { bbox }) +turf.random('polygons', 100, { + bbox, + num_vertices: 10, max_radial_length: 10 -}); - -// -- Test remove -- -var filtered = turf.remove(points, 'marker-color', '#00f'); +}) // -- Test sample -- -var randomPoints = turf.random('points', 1000); -var sample = turf.sample(points, 10); +turf.random('points', 100) +turf.sample(points, 10) /////////////////////////////////////////// // Tests Interpolation /////////////////////////////////////////// // -- Test hexGrid -- -var cellWidth = 50; -var hexgrid = turf.hexGrid(bbox, cellWidth, units); - -// -- Test isolines -- -var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -var isolined = turf.isolines(points, 'z', 15, breaks); - -// -- Test planepoint -- -var zValue = turf.planepoint(point1, triangle); +turf.hexGrid(bbox, 50) +turf.hexGrid(bbox, 50, 'miles') // -- Test pointGrid -- -var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; -var cellWidth = 3; -var grid = turf.pointGrid(extent, cellWidth, units); +turf.pointGrid(bbox, 50) +turf.pointGrid(bbox, 50, 'miles') // -- Test squareGrid -- -var squareGrid = turf.squareGrid(extent, cellWidth, units); - -// -- Test tin -- -var tin = turf.tin(points, 'z'); +turf.squareGrid(bbox, 50) +turf.squareGrid(bbox, 50, 'miles') // -- Test triangleGrid -- -var triangleGrid = turf.triangleGrid(extent, cellWidth, units); +turf.triangleGrid(bbox, 50) +turf.triangleGrid(bbox, 50, 'miles') + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test isolines -- +turf.isolines(points, 'z', 15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + +// -- Test planepoint -- +turf.planepoint(point1, triangle) + +// -- Test tin -- +turf.tin(points, 'z') /////////////////////////////////////////// // Tests Joins /////////////////////////////////////////// // -- Test inside -- -var isInside1 = turf.inside(point1, polygon); +turf.inside(point1, polygon1) // -- Test tag -- -var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); +turf.tag(points, polygons, 'pop', 'population') // -- Test within -- -var ptsWithin = turf.within(points, polygons); +turf.within(points, polygons) /////////////////////////////////////////// // Tests Classification /////////////////////////////////////////// -// -- Test jenks -- -var breaks = turf.jenks(points, 'population', 3); - // -- Test nearest -- -var nearest = turf.nearest(point1, points); +turf.nearest(point1, points) -// -- Test quantile -- -var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// +turf.collect(polygons, points, 'population', 'values') -// -- Test reclass -- -var translations = [ - [0, 200, "small"], - [200, 400, "medium"], - [400, 600, "large"] -]; -var reclassed = turf.reclass(points, 'population', 'size', translations); +/////////////////////////////////////////// +// Tests Assertions +/////////////////////////////////////////// +turf.bbox(polygon1) +turf.bbox(point1) +turf.bbox(lineString1) +turf.bbox(multiLineString1) +turf.bbox(multiPolygon1) \ No newline at end of file diff --git a/turf/turf.d.ts b/turf/turf.d.ts index 647df93398..e90cf69276 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -1,103 +1,130 @@ -// Type definitions for Turf 2.0 +// Type definitions for Turf 3.5.2 // Project: http://turfjs.org/ -// Definitions by: Guillaume Croteau +// Definitions by: Guillaume Croteau , Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/** +#### TODO: + +Update all methods with newest JSDocs & tests based on the latest TurfJS library. + +AGGREGATION +- [x] collect +MEASUREMENT +- [ ] along +- [ ] area +- [ ] bboxPolygon +- [ ] bearing +- [ ] center +- [ ] centroid +- [ ] destination +- [ ] distance +- [ ] envelope +- [ ] lineDistance +- [ ] midpoint +- [ ] pointOnSurface +- [ ] square +TRANSFORMATION +- [ ] bezier +- [ ] buffer +- [ ] concave +- [ ] convex +- [ ] difference +- [ ] intersect +- [ ] simplify +- [ ] union +MISC +- [ ] combine +- [ ] explode +- [ ] flip +- [ ] kinks +- [ ] lineSlice +- [ ] pointOnLine +HELPER +- [x] featureCollection +- [x] feature +- [x] lineString +- [x] multiLineString +- [x] point +- [x] multiPoint +- [x] polygon +- [x] multiPolygon +- [x] geometryCollection +DATA +- [x] random +- [x] sample +INTERPOLATION +- [ ] isolines +- [ ] planepoint +- [ ] tin +JOINS +- [x] inside +- [x] tag +- [ ] within +GRIDS +- [x] hexGrid +- [x] pointGrid +- [x] squareGrid +- [x] triangleGrid +CLASSIFICATION +- [ ] nearest +META +- [ ] propEach +- [ ] coordEach +- [ ] coordReduce +- [ ] featureEach +- [ ] getCoord +ASSERTIONS +- [ ] featureOf +- [ ] collectionOf +- [x] bbox +- [ ] circle +- [ ] geojsonType +- [ ] propReduce +- [ ] coordAll +- [ ] tesselate + */ + +declare const turf: turf.TurfStatic; +declare const TemplateUnits: 'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres' +declare const TemplateType: 'point'| 'points' | 'polygon' | 'polygons' declare module turf { + interface TurfStatic { ////////////////////////////////////////////////////// // Aggregation ////////////////////////////////////////////////////// /** - * Calculates a series of aggregations for a set of points within a set of polygons. - * Sum, average, count, min, max, and deviation are supported. - * @param polygons Polygons with values on which to aggregate - * @param points Points to be aggregated - * @param aggregations An array of aggregation objects - * @returns Polygons with properties listed based on outField values in aggregations - */ - function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; - - /** - * Calculates the average value of a field for a set of points within a set of polygons. - * @param polygons Polygons with values on which to average - * @param points Points from which to calculate the average - * @param field The field in the points features from which to pull values to average - * @param outField The field in polygons to put results of the averages - * @returns Polygons with the value of outField set to the calculated averages - */ - function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param countField A field to append to the attributes of the Polygon features representing Point counts - * @returns Polygons with countField appended - */ - function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the standard deviation value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in points from which to aggregate - * @param outField The field to append to polygons representing deviation - * @returns Polygons with appended field representing deviation - */ - function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the maximum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the median value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the minimum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the sum of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the variance value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + * Merges a specified property from a FeatureCollection of points into a FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty` for polygons, this finds every point that lies within each polygon, collects the `inProperty` values from those points, and adds them as an array to `outProperty` on the polygon. + * + * @name [collect](http://turfjs.org/docs/#collect) + * @param {FeatureCollection} polygons polygons with values on which to aggregate + * @param {FeatureCollection} points points to be aggregated + * @param {string} inProperty property to be nested from + * @param {string} outProperty property to be nested into + * @return {FeatureCollection} polygons with properties listed based on `outField` + * @example + * var poly1 = polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]) + * var poly2 = polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]) + * var polyFC = featurecollection([poly1, poly2]) + * var pt1 = point([5,5], {population: 200}) + * var pt2 = point([1,3], {population: 600}) + * var pt3 = point([14,2], {population: 100}) + * var pt4 = point([13,1], {population: 200}) + * var pt5 = point([19,7], {population: 300}) + * var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5]) + * var aggregated = aggregate(polyFC, ptFC, 'population', 'values') + * + * aggregated.features[0].properties.values // => [200, 600]) + */ + collect( + polygons: GeoJSON.FeatureCollection, + points: GeoJSON.FeatureCollection, + inProperty: string, + outProperty: string + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Measurement @@ -110,21 +137,49 @@ declare module turf { * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' * @returns Point along the line */ - function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + along( + line: GeoJSON.Feature, + distance: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes one or more features and returns their area in square meters. * @param input Input features * @returns Area in square meters */ - function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. + * + * @name bbox + * @param {(Feature|FeatureCollection)} geojson input features + * @return {Array} bbox extent in [minX, minY, maxX, maxY] order + * @example + * var pt1 = point([114.175329, 22.2524]) + * var pt2 = point([114.170007, 22.267969]) + * var pt3 = point([114.200649, 22.274641]) + * var pt4 = point([114.200649, 22.274641]) + * var pt5 = point([114.186744, 22.265745]) + * var features = featureCollection([pt1, pt2, pt3, pt4, pt5]) + * + * var bbox = turf.bbox(features); + * + * var bboxPolygon = turf.bboxPolygon(bbox); + * + * //=bbox + * + * //=bboxPolygon + */ + bbox(bbox: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; /** * Takes a bbox and returns an equivalent polygon. * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] * @returns A Polygon representation of the bounding box */ - function bboxPolygon(bbox: Array): GeoJSON.Feature; + bboxPolygon(bbox: Array): GeoJSON.Feature; /** * Takes two points and finds the geographic bearing between them. @@ -132,14 +187,14 @@ declare module turf { * @param end Ending point * @returns Bearing in decimal degrees */ - function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; /** * Takes a FeatureCollection and returns the absolute center point of all features. * @param features Input features * @returns A Point feature at the absolute center point of all input features */ - function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. @@ -147,10 +202,10 @@ declare module turf { * @param features Input features * @returns The centroid of the input features */ - function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** - * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers and bearing in degrees. * This uses the Haversine formula to account for global curvature. * @param start Starting point * @param distance Distance from the starting point @@ -158,7 +213,12 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Destination point */ - function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + destination( + start: GeoJSON.Feature, + distance: number, + bearing: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Calculates the distance between two points in degress, radians, miles, or kilometers. @@ -168,21 +228,18 @@ declare module turf { * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' * @returns Distance between the two points */ - function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + distance( + from: GeoJSON.Feature, + to: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. * @param fc Input features * @returns A rectangular Polygon feature that encompasses all vertices */ - function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a set of features, calculates the extent of all input features, and returns a bounding box. - * @param input Input features - * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) - */ - function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a line and measures its length in the specified units. @@ -190,7 +247,10 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Length of the input line */ - function lineDistance(line: GeoJSON.Feature, units: string): number; + lineDistance( + line: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes two points and returns a point midway between them. @@ -198,7 +258,7 @@ declare module turf { * @param pt2 Second point * @returns A point midway between pt1 and pt2 */ - function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. @@ -206,22 +266,14 @@ declare module turf { * @param input Any feature or set of features * @returns A point on the surface of input */ - function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. - * @param bbox A bounding box - * @param factor The ratio of the new bbox to the input bbox - * @returns The resized bbox - */ - function size(bbox: Array, factor: number): Array; + pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a bounding box and calculates the minimum square bounding box that would contain the input. * @param bbox A bounding box * @returns A square surrounding bbox */ - function square(bbox: Array): Array; + square(bbox: Array): Array; ////////////////////////////////////////////////////// // Transformation @@ -235,7 +287,7 @@ declare module turf { * @param [sharpness=0.85] A measure of how curvy the path should be between splines * @returns Curved line */ - function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; /** * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. @@ -244,7 +296,14 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Buffered features */ - function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; /** * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. @@ -253,14 +312,20 @@ declare module turf { * @param units Used for maxEdge distance (miles or kilometers) * @returns A concave hull */ - function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + concave( + points: GeoJSON.FeatureCollection, + maxEdge: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. * @param input Input points * @returns A convex hull */ - function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + convex( + input: GeoJSON.FeatureCollection + ): GeoJSON.Feature; /** * Finds the difference between two polygons by clipping the second polygon from the first. @@ -268,26 +333,54 @@ declare module turf { * @param poly2 Polygon feature to difference from poly1 * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 */ - function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + difference( + poly1: GeoJSON.Feature, + poly2: GeoJSON.Feature + ): GeoJSON.Feature; /** - * Takes two polygons and finds their intersection. - * If they share a border, returns the border; if they don't intersect, returns undefined. - * @param poly1 The first polygon - * @param poly2 The second polygon - * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; - * if poly1 and poly2 do not overlap, returns undefined; - * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared - */ - function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; - - /** - * Takes a set of polygons and returns a single merged polygon feature. - * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. - * @param fc Input polygons - * @returns Merged polygon or multipolygon - */ - function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + * Takes two Features and finds their intersection. + * If they share a border, returns the border if they don't intersect, returns undefined. + * + * @name [intersect](http://turfjs.org/docs/#intersect) + * @param {Feature} poly1 + * @param {Feature} poly2 + * @returns {Feature|undefined} A feature representing the point(s) they share (in case of a {Point} or {MultiPoint}), the borders they share (in case of a {LineString} or a {MultiLineString}), the area they share (in case of {Polygon} or {MultiPolygon}). If they do not share any point, returns `undefined`. + * @example + * var poly1 = polygon([[ + * [-122.801742, 45.48565], + * [-122.801742, 45.60491], + * [-122.584762, 45.60491], + * [-122.584762, 45.48565], + * [-122.801742, 45.48565] + * ]]); + * + * var poly2 = polygon([[ + * [-122.520217, 45.535693], + * [-122.64038, 45.553967], + * [-122.720031, 45.526554], + * [-122.669906, 45.507309], + * [-122.723464, 45.446643], + * [-122.532577, 45.408574], + * [-122.487258, 45.477466], + * [-122.520217, 45.535693] + * ]]); + * var polygons = featureCollection([poly1, poly2]); + * + * var intersection = turf.intersect(poly1, poly2); + * + * //=polygons + * + * //=intersection + */ + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; /** * Takes a LineString or Polygon and returns a simplified version. @@ -297,16 +390,16 @@ declare module turf { * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm * @returns A simplified feature */ - function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; /** * Takes two polygons and returns a combined polygon. - * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature.; * @param poly1 Input polygon * @param poly2 Another input polygon * @returns A combined Polygon or MultiPolygon feature */ - function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Misc @@ -317,28 +410,28 @@ declare module turf { * @param fc A FeatureCollection of any type * @returns A FeatureCollection of corresponding type to input */ - function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes a feature or set of features and returns all positions as points. * @param input Input features * @returns Points representing the exploded input features */ - function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes input features and flips all of their coordinates from [x, y] to [y, x]. * @param input Input features * @returns A feature or set of features of the same type as input with flipped coordinates */ - function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; /** * Takes a polygon and returns points at all self-intersections. * @param polygon Input polygon * @returns Self-intersections */ - function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; /** * Takes a line, a start Point, and a stop point and returns the line in between those points. @@ -347,7 +440,7 @@ declare module turf { * @param line Line to slice * @returns Sliced line */ - function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a Point and a LineString and calculates the closest Point on the LineString. @@ -355,98 +448,348 @@ declare module turf { * @param point Point to snap from * @returns Closest point on the line to point */ - function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Helper ////////////////////////////////////////////////////// /** - * Takes one or more Features and creates a FeatureCollection. - * @param features Input features - * @returns A FeatureCollection of input features - */ - function featurecollection(features: Array>): GeoJSON.FeatureCollection; + * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. + * + * @name [featureCollection](http://turfjs.org/docs/#featurecollection) + * @param {Feature[]} features input features + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var features = [ + * turf.point([-75.343, 39.984], {name: 'Location A'}), + * turf.point([-75.833, 39.284], {name: 'Location B'}), + * turf.point([-75.534, 39.123], {name: 'Location C'}) + * ] + * + * var fc = turf.featureCollection(features) + * + * //=fc + */ + featureCollection(features: Array>): GeoJSON.FeatureCollection; /** - * Creates a LineString based on a coordinate array. Properties can be added optionally. - * @param coordinates An array of Positions - * @param [properties] An Object of key-value pairs to add as properties - * @returns A LineString feature - */ - function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}. + * + * @name [feature](http://turfjs.org/docs/#feature) + * @param {Geometry} geometry input geometry + * @param {Object} properties properties + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var geometry = { + * "type": "Point", + * "coordinates": [ + * 67.5, + * 32.84267363195431 + * ] + * } + * + * var feature = turf.feature(geometry) + * + * //=feature + */ + feature(geometry:GeoJSON.Feature, properties?: any): GeoJSON.Feature; /** - * Takes coordinates and properties (optional) and returns a new Point feature. - * @param coordinates Longitude, latitude position (each in decimal degrees) - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Point feature - */ - function point(coordinates: Array, properties?: any): GeoJSON.Feature; + * Creates a {@link LineString} based on a coordinate array. Properties can be added optionally. + * + * @name [lineString](http://turfjs.org/docs/#linestring) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a LineString feature + * @throws {Error} if no coordinates are passed + * @example + * var linestring1 = turf.lineString([ + * [-21.964416, 64.148203], + * [-21.956176, 64.141316], + * [-21.93901, 64.135924], + * [-21.927337, 64.136673] + * ]) + * var linestring2 = turf.lineString([ + * [-21.929054, 64.127985], + * [-21.912918, 64.134726], + * [-21.916007, 64.141016], + * [-21.930084, 64.14446] + * ], {name: 'line 1', distance: 145}) + * + * //=linestring1 + * + * //=linestring2 + */ + lineString(coordinates: Array>, properties?: any): GeoJSON.Feature; /** - * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. - * @param rings An array of LinearRings - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Polygon feature - */ - function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiLineString](http://turfjs.org/docs/#multilinestring) + * @param {Array>>} coordinates an array of LineStrings + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiLineString feature + * @throws {Error} if no coordinates are passed + * @example + * var multiLine = turf.multiLineString([[[0,0],[10,10]]]) + * + * //=multiLine + * + */ + multiLineString(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new {@link Point} feature. + * + * @name [point](http://turfjs.org/docs/#point) + * @param {Array} coordinates longitude, latitude position (each in decimal degrees) + * @param {Object=} properties an Object that is used as the {@link Feature}'s + * properties + * @returns {Feature} a Point feature + * @example + * var pt1 = turf.point([-75.343, 39.984]); + * + * //=pt1 + */ + point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPoint](http://turfjs.org/docs/#multipoint) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiPoint feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPt = turf.multiPoint([[0,0],[10,10]]) + * + * //=multiPt + * + */ + multiPoint(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. + * + * @name [polygon](http://turfjs.org/docs/#polygon) + * @param {Array>>} coordinates an array of LinearRings + * @param {Object=} properties a properties object + * @returns {Feature} a Polygon feature + * @throws {Error} throw an error if a LinearRing of the polygon has too few positions + * or if a LinearRing of the Polygon does not have matching Positions at the + * beginning & end. + * @example + * var polygon = turf.polygon([[ + * [-2.275543, 53.464547], + * [-2.275543, 53.489271], + * [-2.215118, 53.489271], + * [-2.215118, 53.464547], + * [-2.275543, 53.464547] + * ]], { name: 'poly1', population: 400}); + * + * //=polygon + */ + polygon(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPolygon](http://turfjs.org/docs/#multipolygon) + * @param {Array>>>} coordinates an array of Polygons + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a multipolygon feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]); + * + * //=multiPoly + * + */ + multiPolygon(coordinates: Array>>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on acoordinate array. Properties can be added optionally. + * + * @name [geometryCollection](http://turfjs.org/docs/#geometrycollection) + * @param {Array<{Geometry}>} geometries an array of GeoJSON Geometries + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a GeoJSON GeometryCollection Feature + * @example + * var point = { + * "type": "Point", + * "coordinates": [100, 0] + * }; + * var line = { + * "type": "LineString", + * "coordinates": [ [101, 0], [102, 1] ] + * }; + * var collection = turf.geometryCollection([point, line]); + * + * //=collection + */ + geometryCollection(geometries: Array, properties?: any): GeoJSON.GeometryCollection; ////////////////////////////////////////////////////// // Data ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection and filters it by a given property and value. - * @param features Input features - * @param key The property on which to filter - * @param value The value of that property on which to filter - * @returns A filtered collection with only features that match input key and value - */ - function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + * Generates random {@link GeoJSON} data, including {@link Point|Points} and {@link Polygon|Polygons}, for testing and experimentation. + * + * @name [random](http://turfjs.org/docs/#random) + * @param {String} [type='point'] type of features desired: 'points' or 'polygons' + * @param {Number} [count=1] how many geometries should be generated. + * @param {Object} options options relevant to the feature desired. Can include: + * @param {Array} options.bbox a bounding box inside of which geometries + * are placed. In the case of {@link Point} features, they are guaranteed to be within this bounds, + * while {@link Polygon} features have their centroid within the bounds. + * @param {Number} [options.num_vertices=10] options.vertices the number of vertices added + * to polygon features. + * @param {Number} [options.max_radial_length=10] the total number of decimal + * degrees longitude or latitude that a polygon can extent outwards to + * from its center. + * @return {FeatureCollection} generated random features + * @example + * var points = turf.random('points', 100, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=points + * + * var polygons = turf.random('polygons', 4, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=polygons + */ + random(type?: typeof TemplateType, count?: number, options?: { + bbox?: Array + num_vertices?: number + max_radial_length?: number + }): GeoJSON.FeatureCollection; /** - * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. - * @param [type='point'] Type of features desired: 'points' or 'polygons' - * @param [count=1] How many geometries should be generated. - * @param [options] Options relevant to the feature desired. Can include: - * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. - * - The number of vertices added to polygon features. Default is 10; - * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. - * @returns Generated random features - */ - function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. + * + * @name [sample](http://turfjs.org/docs/#sample) + * @param {FeatureCollection} featurecollection set of input features + * @param {number} num number of features to select + * @return {FeatureCollection} a FeatureCollection with `n` features + * @example + * var points = turf.random('points', 1000); + * + * //=points + * + * var sample = turf.sample(points, 10); + * + * //=sample + */ + sample(featurecollection: GeoJSON.FeatureCollection, num: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // GRIDS + ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. - * @param features Set of input features - * @param property The property to remove - * @param value The value to remove - * @returns The resulting FeatureCollection without features that match the property-value pair - */ - function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). + * + * @name [hexGrid](http://turfjs.org/docs/#hexgrid) + * @param {Array} bbox bounding box in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of cell in specified units + * @param {string} units used in calculating cellSize ('miles' or 'kilometers') + * @param {boolean} triangles whether to return as triangles instead of hexagons + * @return {FeatureCollection} a hexagonal grid + * @example + * var bbox = [-96,31,-84,40]; + * var cellSize = 50; + * var units = 'miles'; + * + * var hexgrid = turf.hexGrid(bbox, cellSize, units); + * + * //=hexgrid + */ + hexGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits, + triangles?: boolean + ): GeoJSON.FeatureCollection; /** - * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. - * @param features Set of input features - * @param n Number of features to select - * @returns A FeatureCollection with n features - */ - function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell depth and returns a set of {@link Point|points} in a grid. + * + * @name [pointGrid](http://turfjs.org/docs/#pointgrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize the distance across each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of points + * @example + * var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; + * var cellSize = 3; + * var units = 'miles'; + * + * var grid = turf.pointGrid(extent, cellSize, units); + * + * //=grid + */ + pointGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square {@link Polygon|polygons} in a grid. + * + * @name [squareGrid](http://turfjs.org/docs/#squaregrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize width of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid a grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10 + * var units = 'miles' + * + * var squareGrid = turf.squareGrid(bbox, cellSize, units) + * + * //=squareGrid + */ + squareGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid. + * + * @name [triangleGrid](http://turfjs.org/docs/#trianglegrid)) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10; + * var units = 'miles'; + * + * var triangleGrid = turf.triangleGrid(extent, cellSize, units); + * + * //=triangleGrid + */ + triangleGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Interpolation ////////////////////////////////////////////////////// - /** - * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. - * @param bbox Bounding box in [minX, minY, maxX, maxY] order - * @param cellWidth Width of cell in specified units - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns A hexagonal grid - */ - function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - /** * Takes points with z-values and an array of value breaks and generates isolines. * @param points Input points @@ -455,7 +798,7 @@ declare module turf { * @param breaks Where to draw contours * @returns Isolines */ - function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; /** * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. @@ -464,25 +807,7 @@ declare module turf { * @param triangle A Polygon feature with three vertices * @returns The z-value for interpolatedPoint */ - function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; - - /** - * Takes a bounding box and a cell depth and returns a set of points in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth The distance across each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of points - */ - function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of polygons - */ - function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; /** * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. @@ -492,39 +817,59 @@ declare module turf { * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. * @returns TIN output */ - function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of triangles - */ - function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Joins ////////////////////////////////////////////////////// /** - * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. - * The polygon can be convex or concave. The function accounts for holes. - * @param point Input point - * @param polygon Input polygon or multipolygon - * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon - */ - function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + * Takes a {} and a {} or {} and determines if the point resides inside the polygon. The polygon can be convex or concave. The function accounts for holes. + * + * @name [inside](http://turfjs.org/docs/#inside) + * @param {Feature} point input point + * @param {Feature<(Polygon|MultiPolygon)>} polygon input polygon or multipolygon + * @return {Boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon + * @example + * var pt = point([-77, 44]) + * var poly = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]]) + * + * var isInside = turf.inside(pt, poly) + * + * //=isInside + */ + inside( + point: GeoJSON.Feature, + polygon: GeoJSON.Feature + ): boolean; /** - * Takes a set of points and a set of polygons and performs a spatial join. - * @param points Input points - * @param polygons Input polygons - * @param polyId Property in polygons to add to joined Point features - * @param containingPolyId Property in points in which to store joined property from polygons - * @returns Points with containingPolyId property containing values from polyId - */ - function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + * Takes a {FeatureCollection} and a {FeatureCollection} and performs a spatial join. + * + * @name [tag](http://turfjs.org/docs/#inside) + * @param {FeatureCollection} points input points + * @param {FeatureCollection} polygons input polygons + * @param {string} field property in `polygons` to add to joined {} features + * @param {string} outField property in `points` in which to store joined property from `polygons` + * @return {FeatureCollection} points with `containingPolyId` property containing values from `polyId` + * @example + * var pt1 = point([-77, 44]) + * var pt2 = point([-77, 38]) + * var poly1 = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]], {pop: 1000}) + * var poly2 = polygon([[[-81, 35], [-81, 41], [-72, 41], [-72, 35], [-81, 35]]], {pop: 3000}) + * + * var points = featureCollection([pt1, pt2]) + * var polygons = featureCollection([poly1, poly2]) + * + * var tagged = turf.tag(points, polygons, 'pop', 'population') + * //=tagged + */ + tag( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection, + field: string, + outField: string + ): GeoJSON.FeatureCollection; /** * Takes a set of points and a set of polygons and returns the points that fall within the polygons. @@ -532,49 +877,331 @@ declare module turf { * @param polygons Input polygons * @returns Points that land within at least one polygon */ - function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + within( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Classification ////////////////////////////////////////////////////// - /** - * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. - * @param input Input features - * @param field The property in input on which to calculate Jenks natural breaks - * @param numberOfBreaks Number of classes in which to group the data - * @returns The break number for each class plus the minimum and maximum values - */ - function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; - /** * Takes a reference point and a set of points and returns the point from the set closest to the reference. * @param point The reference point * @param against Input point set * @returns The closest point in the set to the reference point */ - function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. - * @param input Set of features - * @param field The property in input from which to retrieve quantile values - * @param percentiles An Array of percentiles on which to calculate quantile values - * @returns An array of the break values - */ - function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; - - /** - * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. - * @param input Set of input features - * @param inField The field to translate - * @param outField The field in which to store translated results - * @param translations An array of translations - * @returns A FeatureCollection with identical geometries to input but with outField populated. - */ - function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; + nearest( + point: GeoJSON.Feature, + against: GeoJSON.FeatureCollection + ): GeoJSON.Feature; + } } -declare module 'turf' { - export= turf; +// NPM Stable version of Turf +declare module "turf" { + export = turf } + +// Latest version of Turf +declare module "@turf/turf" { + export = turf +} + +// AGGREGATION +declare module "@turf/collect" { + const collect: typeof turf.collect; + export = collect; +} + +// MEASUREMENT +declare module "@turf/along" { + const along: typeof turf.along; + export = along; +} + +declare module "@turf/area" { + const area: typeof turf.area; + export = area; +} + +declare module "@turf/bbox-polygon" { + const bboxPolygon: typeof turf.bboxPolygon; + export = bboxPolygon; +} + +declare module "@turf/bearing" { + const bearing: typeof turf.bearing; + export = bearing; +} + +declare module "@turf/center" { + const center: typeof turf.center; + export = center; +} + +declare module "@turf/centroid" { + const centroid: typeof turf.centroid; + export = centroid; +} + +declare module "@turf/destination" { + const destination: typeof turf.destination; + export = destination; +} + +declare module "@turf/distance" { + const distance: typeof turf.distance; + export = distance; +} + +declare module "@turf/envelope" { + const envelope: typeof turf.envelope; + export = envelope; +} + +declare module "@turf/line-distance" { + const lineDistance: typeof turf.lineDistance; + export = lineDistance; +} + +declare module "@turf/midpoint" { + const midpoint: typeof turf.midpoint; + export = midpoint; +} + +declare module "@turf/point-on-surface" { + const pointOnSurface: typeof turf.pointOnSurface; + export = pointOnSurface; +} + +declare module "@turf/square" { + const square: typeof turf.square; + export = square; +} + +// TRANSFORMATION +declare module "@turf/bezier" { + const bezier: typeof turf.bezier; + export = bezier; +} + +declare module "@turf/buffer" { + const buffer: typeof turf.buffer; + export = buffer; +} + +declare module "@turf/concave" { + const concave: typeof turf.concave; + export = concave; +} + +declare module "@turf/convex" { + const convex: typeof turf.convex; + export = convex; +} + +declare module "@turf/difference" { + const difference: typeof turf.difference; + export = difference; +} + +declare module "@turf/intersect" { + const intersect: typeof turf.intersect; + export = intersect; +} + +declare module "@turf/simplify" { + const simplify: typeof turf.simplify; + export = simplify; +} + +declare module "@turf/union" { + const union: typeof turf.union; + export = union; +} + +// MISC +declare module "@turf/combine" { + const combine: typeof turf.combine; + export = combine; +} + +declare module "@turf/explode" { + const explode: typeof turf.explode; + export = explode; +} + +declare module "@turf/flip" { + const flip: typeof turf.flip; + export = flip; +} + +declare module "@turf/kinks" { + const kinks: typeof turf.kinks; + export = kinks; +} + +declare module "@turf/line-slice" { + const lineSlice: typeof turf.lineSlice; + export = lineSlice; +} + +declare module "@turf/point-on-line" { + const pointOnLine: typeof turf.pointOnLine; + export = pointOnLine; +} + +// HELPER +declare module "@turf/helpers" { + const helpers: { + featureCollection: typeof turf.featureCollection, + feature: typeof turf.feature, + lineString: typeof turf.lineString, + multiLineString: typeof turf.multiLineString, + point: typeof turf.point, + multiPoint: typeof turf.multiPoint, + polygon: typeof turf.polygon, + multiPolygon: typeof turf.multiPolygon, + geometryCollection: typeof turf.geometryCollection, + }; + export = helpers; +} + +// DATA +declare module "@turf/random" { + const random: typeof turf.random; + export = random; +} + +declare module "@turf/sample" { + const sample: typeof turf.sample; + export = sample; +} + +// INTERPOLATION +declare module "@turf/isolines" { + const isolines: typeof turf.isolines; + export = isolines; +} + +declare module "@turf/planepoint" { + const planepoint: typeof turf.planepoint; + export = planepoint; +} + +declare module "@turf/tin" { + const tin: typeof turf.tin; + export = tin; +} + +// JOINS +declare module "@turf/inside" { + const inside: typeof turf.inside; + export = inside; +} + +declare module "@turf/tag" { + const tag: typeof turf.tag; + export = tag; +} + +declare module "@turf/within" { + const within: typeof turf.within; + export = within; +} + +// GRIDS +declare module "@turf/hex-grid" { + const hexGrid: typeof turf.hexGrid; + export = hexGrid; +} + +declare module "@turf/point-grid" { + const pointGrid: typeof turf.pointGrid; + export = pointGrid; +} + +declare module "@turf/square-grid" { + const squareGrid: typeof turf.squareGrid; + export = squareGrid; +} + +declare module "@turf/triangle-grid" { + const triangleGrid: typeof turf.triangleGrid; + export = triangleGrid; +} + +// CLASSIFICATION +declare module "@turf/nearest" { + const nearest: typeof turf.nearest; + export = nearest; +} + +// // META +// declare module "@turf/propEach" { +// const propEach: typeof turf.propEach; +// export = propEach; +// } + +// declare module "@turf/coordEach" { +// const coordEach: typeof turf.coordEach; +// export = coordEach; +// } + +// declare module "@turf/coordReduce" { +// const coordReduce: typeof turf.coordReduce; +// export = coordReduce; +// } + +// declare module "@turf/featureEach" { +// const featureEach: typeof turf.featureEach; +// export = featureEach; +// } + +// declare module "@turf/getCoord" { +// const getCoord: typeof turf.getCoord; +// export = getCoord; +// } + +// // ASSERTIONS +// declare module "@turf/featureOf" { +// const featureOf: typeof turf.featureOf; +// export = featureOf; +// } + +// declare module "@turf/collectionOf" { +// const collectionOf: typeof turf.collectionOf; +// export = collectionOf; +// } + +declare module "@turf/bbox" { + const bbox: typeof turf.bbox; + export = bbox; +} + +// declare module "@turf/circle" { +// const circle: typeof turf.circle; +// export = circle; +// } + +// declare module "@turf/geojsonType" { +// const geojsonType: typeof turf.geojsonType; +// export = geojsonType; +// } + +// declare module "@turf/propReduce" { +// const propReduce: typeof turf.propReduce; +// export = propReduce; +// } + +// declare module "@turf/coordAll" { +// const coordAll: typeof turf.coordAll; +// export = coordAll; +// } + +// declare module "@turf/tesselate" { +// const tesselate: typeof turf.tesselate; +// export = tesselate; +// } From ee9a6159396bdfde7d345df6e6b5cdf57fdb9bcc Mon Sep 17 00:00:00 2001 From: Borislav Zhivkov Date: Mon, 19 Sep 2016 09:51:04 +0300 Subject: [PATCH 070/154] Add angular-feature-flags definitions (#11283) --- .../angular-feature-flags-tests.ts | 31 +++++++++++++++ .../angular-feature-flags.d.ts | 38 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 angular-feature-flags/angular-feature-flags-tests.ts create mode 100644 angular-feature-flags/angular-feature-flags.d.ts diff --git a/angular-feature-flags/angular-feature-flags-tests.ts b/angular-feature-flags/angular-feature-flags-tests.ts new file mode 100644 index 0000000000..a36eaba3d0 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags-tests.ts @@ -0,0 +1,31 @@ +/// + +let myApp = angular.module('myApp', ['feature-flags']); + +const flagsData: Array = [ + { + key: '1', + active: true, + name: 'flag1', + description: 'This is the first flag' + }, + { + key: '2', + active: false, + name: 'flag2', + description: 'This is the second flag' + } +]; + +myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) { + featureFlagsProvider.setInitialFlags(flagsData); +}); + +myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) { + let deferred = $q.defer(); + deferred.resolve(flagsData); + + featureFlags.set(deferred.promise); + + featureFlags.set($http.get('/data/flags.json')); +}); \ No newline at end of file diff --git a/angular-feature-flags/angular-feature-flags.d.ts b/angular-feature-flags/angular-feature-flags.d.ts new file mode 100644 index 0000000000..99ef300976 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags.d.ts @@ -0,0 +1,38 @@ +// Type definitions for angular-feature-flags 1.4.0 +// Project: https://github.com/mjt01/angular-feature-flags +// Definitions by: Borislav Zhivkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.featureflags { + export interface FlagData { + /** + * Unique key that is used from the markup to resolve whether a flag is active or not. + */ + key: string; + + /** + * Boolean value for enabling/disabling the feature + */ + active: boolean; + + /** + * A short name of the flag (only visible in the list of flags) + */ + name: string; + + /** + * A long description of the flag to further explain the feature being toggled (only visible in the list of flags) + */ + description: string; + } + + export interface FeatureFlagsProvider { + setInitialFlags(flags: Array): void; + } + + export interface FeatureFlagsService { + set(flagsPromise: angular.IPromise | angular.IHttpPromise): void; + } +} \ No newline at end of file From 4b8264149240480dec8d6d6b2dd97ddaedba4142 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sun, 18 Sep 2016 23:56:50 -0700 Subject: [PATCH 071/154] Update to Electron 1.3.6 (#11229) --- github-electron/github-electron.d.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 3dc72d7075..64b7cf6a02 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.5 +// Type definitions for Electron v1.3.6 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -62,7 +62,7 @@ declare namespace Electron { /** * Emitted when Electron has finished initialization. */ - on(event: 'ready', listener: Function): this; + on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this; /** * Emitted when all windows have been closed. * @@ -218,6 +218,10 @@ declare namespace Electron { args?: string[], execPath?: string }): void; + /** + * @returns Whether Electron has finished initializing. + */ + isReady(): boolean; /** * On Linux, focuses on the first visible window. * On macOS, makes the application the active app. @@ -1367,6 +1371,12 @@ declare namespace Electron { } interface WebPreferences { + /** + * Whether to enable DevTools. + * If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. + * Default: true. + */ + devTools?: boolean; /** * Whether node integration is enabled. * Default: true. @@ -1957,7 +1967,7 @@ declare namespace Electron { interface CrashReporterStartOptions { /** - * Default: Electron + * Default: app.getName() */ productName?: string; companyName: string; @@ -3392,16 +3402,18 @@ declare namespace Electron { interface Shell { /** * Show the given file in a file manager. If possible, select the file. + * @returns Whether the item was successfully shown. */ - showItemInFolder(fullPath: string): void; + showItemInFolder(fullPath: string): boolean; /** * Open the given file in the desktop's default manner. + * @returns Whether the item was successfully shown. */ - openItem(fullPath: string): void; + openItem(fullPath: string): boolean; /** * Open the given external protocol URL in the desktop's default manner * (e.g., mailto: URLs in the default mail user agent). - * @returns true if an application was available to open the URL, false otherwise. + * @returns Whether an application was available to open the URL. */ openExternal(url: string, options?: { /** @@ -3412,7 +3424,7 @@ declare namespace Electron { }): boolean; /** * Move the given file to trash. - * @returns boolean status for the operation. + * @returns Whether the item was successfully moved to the trash. */ moveItemToTrash(fullPath: string): boolean; /** From 1adaa22d7a6cc83ce09638e2cae00fc6f6589857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Mon, 19 Sep 2016 01:07:25 -0600 Subject: [PATCH 072/154] [WIP] Add type definitions for Leaflet 1.0 (#11165) * Rename leaflet.d.ts to leaflet-0.7.d.ts * Defined several important interfaces and the skeleton of some others * Started adding tests * Added more interfaces, factory methods and tests * Implemented other interfaces and nested namespaces * Added more types --- heatmap.js/heatmap.d.ts | 2 +- leaflet-curve/leaflet-curve-tests.ts | 2 +- leaflet-curve/leaflet-curve.d.ts | 2 +- leaflet-draw/leaflet-draw-tests.ts | 4 +- leaflet-draw/leaflet-draw.d.ts | 2 +- leaflet-editable/leaflet-editable.d.ts | 2 +- .../leaflet-geocoder-mapzen-tests.ts | 2 +- .../leaflet-geocoder-mapzen.d.ts | 2 +- leaflet-label/leaflet-label.d.ts | 2 +- .../leaflet-markercluster.d.ts | 8 +- .../leaflet.awesome-markers.d.ts | 2 +- leaflet.fullscreen/leaflet.fullscreen.d.ts | 2 +- leaflet/leaflet-0.7-tests.ts | 427 ++ leaflet/leaflet-0.7.d.ts | 4382 ++++++++++++++ leaflet/leaflet-tests.ts | 690 +-- leaflet/leaflet.d.ts | 5095 +++-------------- mapbox/mapbox.d.ts | 2 +- 17 files changed, 5911 insertions(+), 4717 deletions(-) create mode 100644 leaflet/leaflet-0.7-tests.ts create mode 100644 leaflet/leaflet-0.7.d.ts diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 7cd14fc214..fb2b4eea3d 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -3,7 +3,7 @@ // Definitions by: Yang Guan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /* * Configuration object of a heatmap diff --git a/leaflet-curve/leaflet-curve-tests.ts b/leaflet-curve/leaflet-curve-tests.ts index 2c5bb6b8f1..9864e71252 100644 --- a/leaflet-curve/leaflet-curve-tests.ts +++ b/leaflet-curve/leaflet-curve-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// diff --git a/leaflet-curve/leaflet-curve.d.ts b/leaflet-curve/leaflet-curve.d.ts index 32358c08ac..7bd64215b9 100644 --- a/leaflet-curve/leaflet-curve.d.ts +++ b/leaflet-curve/leaflet-curve.d.ts @@ -3,7 +3,7 @@ // Definitions by: Onikiienko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { /** diff --git a/leaflet-draw/leaflet-draw-tests.ts b/leaflet-draw/leaflet-draw-tests.ts index 9a1ed09306..396f5119d3 100644 --- a/leaflet-draw/leaflet-draw-tests.ts +++ b/leaflet-draw/leaflet-draw-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// @@ -44,4 +44,4 @@ map.on('draw:created', function (e: L.DrawEvents.Created) { layer = e.layer; drawnItems.addLayer(layer); -}); \ No newline at end of file +}); diff --git a/leaflet-draw/leaflet-draw.d.ts b/leaflet-draw/leaflet-draw.d.ts index 253d6c3a11..7c80f17ef2 100644 --- a/leaflet-draw/leaflet-draw.d.ts +++ b/leaflet-draw/leaflet-draw.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Guest // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface MapOptions { diff --git a/leaflet-editable/leaflet-editable.d.ts b/leaflet-editable/leaflet-editable.d.ts index 0d7b2bcc0f..f559917b62 100644 --- a/leaflet-editable/leaflet-editable.d.ts +++ b/leaflet-editable/leaflet-editable.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dominic Alie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { /** diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts index c6519ab371..d623120a73 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts index 8809472e43..3e388ff515 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { namespace Control { diff --git a/leaflet-label/leaflet-label.d.ts b/leaflet-label/leaflet-label.d.ts index 009ded17f8..ea18df3cea 100644 --- a/leaflet-label/leaflet-label.d.ts +++ b/leaflet-label/leaflet-label.d.ts @@ -3,7 +3,7 @@ // Definitions by: Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface IconOptions { diff --git a/leaflet-markercluster/leaflet-markercluster.d.ts b/leaflet-markercluster/leaflet-markercluster.d.ts index 7d8757be03..b756389275 100644 --- a/leaflet-markercluster/leaflet-markercluster.d.ts +++ b/leaflet-markercluster/leaflet-markercluster.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface MarkerClusterGroupOptions { @@ -51,7 +51,7 @@ declare namespace L { /* * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * Decreasing will make more, smaller clusters. You can also use a function that accepts + * Decreasing will make more, smaller clusters. You can also use a function that accepts * the current map zoom and returns the maximum cluster radius in pixels */ maxClusterRadius?: number | ((zoom: number) => number); @@ -134,9 +134,9 @@ declare namespace L { getAllChildMarkers(): Marker[]; /* - * Zooms to show the given marker (spiderfying if required), + * Zooms to show the given marker (spiderfying if required), * calls the callback when the marker is visible on the map. - */ + */ zoomToShowLayer(layer: any, callback: () => void): void; } } diff --git a/leaflet.awesome-markers/leaflet.awesome-markers.d.ts b/leaflet.awesome-markers/leaflet.awesome-markers.d.ts index 6fa754ad8d..4364743d48 100644 --- a/leaflet.awesome-markers/leaflet.awesome-markers.d.ts +++ b/leaflet.awesome-markers/leaflet.awesome-markers.d.ts @@ -3,7 +3,7 @@ // Definitions by: Egor Komarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module L { module AwesomeMarkers { diff --git a/leaflet.fullscreen/leaflet.fullscreen.d.ts b/leaflet.fullscreen/leaflet.fullscreen.d.ts index b8be6604dc..f094c307dc 100644 --- a/leaflet.fullscreen/leaflet.fullscreen.d.ts +++ b/leaflet.fullscreen/leaflet.fullscreen.d.ts @@ -3,7 +3,7 @@ // Definitions by: William Comartin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { diff --git a/leaflet/leaflet-0.7-tests.ts b/leaflet/leaflet-0.7-tests.ts new file mode 100644 index 0000000000..1a88096002 --- /dev/null +++ b/leaflet/leaflet-0.7-tests.ts @@ -0,0 +1,427 @@ +/// + +// initialize the map on the "map" div with a given center and zoom + +var div = document.getElementById('map'); + +var map : L.Map = L.map(div, { + center: L.latLng([51.505, -0.09]), + zoom: 13, + minZoom: 3, + maxZoom: 8, + maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), + dragging: true, + touchZoom: true, + scrollWheelZoom: true, + boxZoom: true, + tap: true, + + tapTolerance: 30, + trackResize: true, + worldCopyJump: false, + closePopupOnClick: true, + bounceAtZoomLimits: true, + + keyboard: true, + keyboardPanOffset: 80, + keyboardZoomOffset: 1, + + inertia: true, + inertiaDeceleration: 3000, + inertiaMaxSpeed: 1500, + inertiaThreshold: 32, + + zoomControl: true, + attributionControl: true, + + fadeAnimation: true, + zoomAnimation: true, + zoomAnimationThreshold: 4, + markerZoomAnimation: true + +}); + +map.dragging.enable(); +map.touchZoom.enable(); +map.scrollWheelZoom.enable(); +map.doubleClickZoom.enable(); +map.boxZoom.enable(); +map.tap.enable(); + +map.setView(new L.LatLng(42, 51)); +map.setView(L.latLng(42, 51)); + +map.setView(L.latLng(42, 51), 12); +map.setView(L.latLng(42, 51), 12, { + reset: true, + pan: { + animate: true, + duration: 0.25, + easeLinearity: 0.25, + noMoveStart: false + }, + zoom: { + animate: true + } +}); + +map.setZoom(50); +map.setZoom(50, {}); + +map.zoomIn(); +map.zoomOut(); + +map.zoomIn(2); +map.zoomOut(2); + +map.zoomIn(2, { animate: true }); +map.zoomOut(2, { animate: true }); + +map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); + +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { + paddingTopLeft: L.point(20, 20), + paddingBottomRight: L.point(20, 20), + padding: L.point(0, 0), + maxZoom: null +}); + +map.fitWorld(); + +map.fitWorld({ + animate: false +}); + +map.panTo(L.latLng(42, 42)); +map.panTo(L.latLng(42, 42), { + animate: true +}); + +map.invalidateSize(true); +map.invalidateSize({ reset: true }); + +map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); + +map.locate(); +map.locate({ + watch: false, + setView: false, + maxZoom: 18, + timeout: 10000, + maximumAge: 0, + enableHighAccuracy: false +}); + +map.stopLocate(); + +map.remove(); + +var center : L.LatLng = map.getCenter(); +var zoom : number = map.getZoom(); +var minZoom: number = map.getMinZoom(); +var maxZoom: number = map.getMaxZoom(); +var bounds: L.LatLngBounds = map.getBounds(); +var boundsZoom: number = map.getBoundsZoom(bounds, true); +var size: L.Point = map.getSize(); +var pixelBounds: L.Bounds = map.getPixelBounds(); +var pixelOrigin: L.Point = map.getPixelOrigin(); + +var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); + +map.addLayer(layer); +map.addLayer(layer, false); +map.eachLayer(l => {}); + +map.removeLayer(layer); +map.hasLayer(layer); + +map.openPopup("canard", L.latLng(42, 51)); + +var popup = L.popup({ + autoPan: true +}); + +map.openPopup(popup); +map.closePopup(popup); +map.closePopup(); + +map.addControl(L.control.attribution({position: 'bottomright'})); +map.removeControl(L.control.attribution({ position: 'bottomright' })); + +L.control.layers({'Base': layer}).addTo(map); +map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) { + alert(e.name); +}); + +map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); +map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); +map.containerPointToLayerPoint(L.point(0, 0)); +map.layerPointToContainerPoint(L.point(0, 0)); + +map.project(map.unproject(L.point(10, 20))); +map.project(map.unproject(L.point(10, 20), 12), 12); + +var mouseEvent: L.LeafletMouseEvent; +map.mouseEventToContainerPoint(mouseEvent); +map.mouseEventToLayerPoint(mouseEvent); +map.mouseEventToLatLng(mouseEvent); + +map.getContainer().classList.add('roger'); +map.getPanes().mapPane.classList.add('roger'); +map.getPanes().markerPane.classList.add('roger'); +map.getPanes().objectsPane.classList.add('roger'); +map.getPanes().overlayPane.classList.add('roger'); +map.getPanes().popupPane.classList.add('roger'); +map.getPanes().shadowPane.classList.add('roger'); +map.getPanes().tilePane.classList.add('roger'); + +map.whenReady((m: L.Map) => { + m.zoomOut(); +}); + +map.on('click', () => { + map.zoomOut(); +}); + +map.off('dblclick', L.Util.falseFn); + +map.once('contextmenu', (e: L.LeafletMouseEvent) => { + map.openPopup('contextmenu', e.latlng); +}); + +var marker = L.marker(L.latLng(42, 51), { + icon: L.icon({ + iconUrl: 'roger.png', + iconRetinaUrl: 'roger-retina.png', + iconSize: L.point(40, 40), + iconAnchor: L.point(20, 0), + shadowUrl: 'roger-shadow.png', + shadowRetinaUrl: 'roger-shadow-retina.png', + shadowSize: L.point(44, 44), + shadowAnchor: L.point(22, 0), + popupAnchor: L.point(0, 0), + className: 'roger-icon' + }), + clickable: true, + draggable: false, + keyboard: true, + title: 'this is an icon', + alt: '', + zIndexOffset: 0, + opacity: 1.0, + riseOnHover: false, + riseOffset: 250 +}); + +marker.addTo(map); + +marker.on('click', (e: L.LeafletMouseEvent) => { + map.setView(e.latlng); +}); + +marker.once('mouseover', () => { + marker.openPopup(); +}) + +marker.setLatLng(marker.getLatLng()); + +marker.setIcon(L.icon({})); + +marker.setZIndexOffset(30); +marker.setOpacity(0.8); + +marker.bindPopup(popup); +marker.unbindPopup(); +marker.bindPopup('hello', { + closeOnClick: true +}); + +marker.openPopup(); +marker.closePopup(); +marker.togglePopup(); +marker.togglePopup(); +marker.setPopupContent('hello 3') +marker.getPopup().setContent('hello 2'); +marker.update(); + +marker.toGeoJSON(); + +marker.dragging.enable(); + +popup = L.popup({ + maxWidth: 300, + minWidth: 50, + maxHeight: null, + autoPan: true, + keepInView: false, + closeButton: true, + offset: L.point(0, 6), + autoPanPaddingTopLeft: null, + autoPanPaddingBottomRight: L.point(20, 20), + autoPanPadding: L.point(5, 5), + zoomAnimation: true, + closeOnClick: null, + className: 'roger' +}); + +popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); + +popup.update(); + +var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 17, + tileSize: 256, + subdomains: ['a','b','c'], + errorTileUrl: '', + attribution: '', + tms: false, + continuousWorld: false, + noWrap: false, + zoomOffset: 0, + zoomReverse: false, + opacity: 1.0, + zIndex: null, + unloadInvisibleTiles: false, + updateWhenIdle: false, + detectRetina: true, + reuseTiles: true, + bounds: null +}); + +tileLayer.on('loading', L.Util.falseFn) + .off('loading', L.Util.falseFn) + .once('tileload', L.Util.falseFn); + +tileLayer.addTo(map); + +tileLayer.bringToBack() + .bringToFront() + .setOpacity(0.7) + .setZIndex(9) + .redraw() + .setUrl('http://perdu.com') + .getContainer(); + +namespace CustomControl { + export interface Options { + title: string; + position?: string; + } +} +interface CustomControl extends L.Control { + getTitle(): string; + setTitle(title: string): CustomControl; +} +var CustomControl: { new(options: CustomControl.Options): CustomControl }; +CustomControl = L.Control.extend({ + initialize: function(options: CustomControl.Options) { + L.Control.prototype.initialize.call(this, { + position: options.position || 'bottomleft', + }); + this.title = options.title; + }, + getTitle: function() { + return this.title; + }, + setTitle: function(title: string) { + this.title = title; + }, +}); + +// Different latLng and latLngBounds expressions +var latLngLiteral = [10, 20]; +var latLngObjectLiteral = { lat: 10, lng: 10 }; +var boundsLiteral = [[10, 20], [20, 20]]; +var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral]; + +var circle: L.Circle = L.circle(latLngLiteral, 4); +circle = new L.Circle(latLngLiteral, 4); +circle.setLatLng(latLngLiteral); + +circle = L.circle(latLngObjectLiteral, 4); +circle = new L.Circle(latLngObjectLiteral, 4); +circle.setLatLng(latLngObjectLiteral); + +var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral); +circleMarker = new L.CircleMarker(latLngLiteral); +circleMarker.setLatLng(latLngLiteral); + +circleMarker = L.circleMarker(latLngObjectLiteral); +circleMarker = new L.CircleMarker(latLngObjectLiteral); +circleMarker.setLatLng(latLngObjectLiteral); + +var latLng: L.LatLng = L.latLng(latLngLiteral); +latLng = new L.LatLng(latLngLiteral); +latLng.distanceTo(latLngLiteral); +latLng.equals(latLngLiteral); + +latLng = L.latLng(latLngObjectLiteral); +latLng = new L.LatLng(latLngObjectLiteral); +latLng.distanceTo(latLngObjectLiteral); +latLng.equals(latLngObjectLiteral); + +var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral); +bounds = L.latLngBounds(boundLiteralOfLatLngObjects); +bounds = new L.LatLngBounds(boundsLiteral); +bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects); +bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); + +bounds.extend(latLngLiteral); +bounds.extend(latLngObjectLiteral); +bounds.extend(boundsLiteral); +bounds.extend(boundLiteralOfLatLngObjects); + +bounds.contains(latLngLiteral); +bounds.contains(boundLiteralOfLatLngObjects); +bounds.contains(boundsLiteral); + +bounds.intersects(boundsLiteral); +bounds.intersects(boundLiteralOfLatLngObjects); + +bounds.equals(boundsLiteral); +bounds.equals(boundLiteralOfLatLngObjects); + +map.setView(latLngLiteral); +map.setView(latLngObjectLiteral); +map.setZoomAround(latLngLiteral, 15); +map.setZoomAround(latLngObjectLiteral, 15); +map.panTo(latLngLiteral); +map.panTo(latLngObjectLiteral); +map.openPopup('test', latLngLiteral); +map.openPopup('test', latLngObjectLiteral); +map.latLngToLayerPoint(latLngLiteral); +map.latLngToLayerPoint(latLngObjectLiteral); +map.latLngToContainerPoint(latLngLiteral); +map.latLngToContainerPoint(latLngObjectLiteral); +map.project(latLngLiteral); +map.project(latLngObjectLiteral); + +marker.setLatLng(latLngLiteral); +marker.setLatLng(latLngObjectLiteral); + +var polygon: L.Polygon = L.polygon(boundsLiteral); +polygon = L.polygon(boundLiteralOfLatLngObjects); +polygon = new L.Polygon(boundsLiteral); +polygon = new L.Polygon(boundLiteralOfLatLngObjects); + +var polyline: L.Polyline = L.polyline(boundsLiteral); +polyline = L.polyline(boundLiteralOfLatLngObjects); +polyline = new L.Polyline(boundsLiteral); +polyline = new L.Polyline(boundLiteralOfLatLngObjects); +polyline.setLatLngs(boundsLiteral); +polyline.setLatLngs(boundLiteralOfLatLngObjects); +polyline.addLatLng(latLngLiteral); +polyline.addLatLng(latLngObjectLiteral); + +var popup: L.Popup = L.popup(); +popup.setLatLng(latLngLiteral); +popup.setLatLng(latLngObjectLiteral); + +var zoomCtrl = L.control.zoom({ + position: "topleft", + zoomInText: '+', + zoomOutText: '-' +}); diff --git a/leaflet/leaflet-0.7.d.ts b/leaflet/leaflet-0.7.d.ts new file mode 100644 index 0000000000..0c4bca15a6 --- /dev/null +++ b/leaflet/leaflet-0.7.d.ts @@ -0,0 +1,4382 @@ +// Type definitions for Leaflet.js 0.7.x +// Project: https://github.com/Leaflet/Leaflet +// Definitions by: Vladimir Zotov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) + type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; + type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; +} + +declare namespace L { + + export interface AttributionOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomright'. + */ + position?: PositionString; + + /** + * The HTML text shown before the attributions. Pass false to disable. + * Default value: 'Powered by Leaflet'. + */ + prefix?: string; + + } +} + +declare namespace L { + + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + export function bounds(points: Point[]): Bounds; + + + export interface BoundsStatic { + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + new(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + new(points: Point[]): Bounds; + } + export var Bounds: BoundsStatic; + + export interface Bounds { + /** + * Extends the bounds to contain the given point. + */ + extend(point: Point): void; + + /** + * Returns the center point of the bounds. + */ + getCenter(): Point; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: Bounds): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(point: Point): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: Bounds): boolean; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + /** + * Returns the size of the given bounds. + */ + getSize(): Point; + + /** + * The top left corner of the rectangle. + */ + min: Point; + + /** + * The bottom right corner of the rectangle. + */ + max: Point; + } +} + +declare namespace L { + + namespace Browser { + + /** + * true for all Internet Explorer versions. + */ + export var ie: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie6: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie7: boolean; + + /** + * true for webkit-based browsers like Chrome and Safari (including mobile + * versions). + */ + export var webkit: boolean; + + /** + * true for webkit-based browsers that support CSS 3D transformations. + */ + export var webkit3d: boolean; + + /** + * true for Android mobile browser. + */ + export var android: boolean; + + /** + * true for old Android stock browsers (2 and 3). + */ + export var android23: boolean; + + /** + * true for modern mobile browsers (including iOS Safari and different Android + * browsers). + */ + export var mobile: boolean; + + /** + * true for mobile webkit-based browsers. + */ + export var mobileWebkit: boolean; + + /** + * true for mobile Opera. + */ + export var mobileOpera: boolean; + + /** + * true for all browsers on touch devices. + */ + export var touch: boolean; + + /** + * true for browsers with Microsoft touch model (e.g. IE10). + */ + export var msTouch: boolean; + + /** + * true for devices with Retina screens. + */ + export var retina: boolean; + + } +} + + +declare namespace L { + + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + + export interface CircleStatic extends ClassStatic { + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + } + export var Circle: CircleStatic; + + export interface Circle extends Path { + /** + * Returns the current geographical position of the circle. + */ + getLatLng(): LatLng; + + /** + * Returns the current radius of a circle. Units are in meters. + */ + getRadius(): number; + + /** + * Sets the position of a circle to a new location. + */ + setLatLng(latlng: LatLngExpression): Circle; + + /** + * Sets the radius of a circle. Units are in meters. + */ + setRadius(radius: number): Circle; + + /** + * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). + */ + toGeoJSON(): GeoJSON.Feature; + + } +} + +declare namespace L { + + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + + + export interface CircleMarkerStatic extends ClassStatic { + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + } + export var CircleMarker: CircleMarkerStatic; + + export interface CircleMarker extends Circle { + /** + * Sets the position of a circle marker to a new location. + */ + setLatLng(latlng: LatLngExpression): CircleMarker; + + /** + * Sets the radius of a circle marker. Units are in pixels. + */ + setRadius(radius: number): CircleMarker; + } +} + +declare namespace L { + export interface ClassExtendOptions { + /** + * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. + */ + initialize?: Function; + + /** + * options is a special property that unlike other objects that you pass + * to extend will be merged with the parent one instead of overriding it + * completely, which makes managing configuration of objects and default + * values convenient. + */ + options?: any; + + /** + * includes is a special class property that merges all specified objects + * into the class (such objects are called mixins). A good example of this + * is L.Mixin.Events that event-related methods like on, off and fire + * to the class. + */ + includes?: any; + + /** + * statics is just a convenience property that injects specified object + * properties as the static properties of the class, useful for defining + * constants. + */ + static?: any; + + [prop: string]: any; + } + + export interface ClassStatic { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + extend(options: ClassExtendOptions): any; + extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; + + /** + * You can also use the following shortcut when you just need to make + * one additional method call. + */ + addInitHook(methodName: string, ...args: any[]): void; + } + + + /** + * L.Class powers the OOP facilities of Leaflet and is used to create + * almost all of the Leaflet classes documented. + */ + namespace Class { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + function extend(options: ClassExtendOptions): any; + } + +} + +declare namespace L { + export interface ControlStatic extends ClassStatic { + /** + * Creates a control with the given options. + */ + new(options?: ControlOptions): Control; + + Zoom: Control.ZoomStatic; + Attribution: Control.AttributionStatic; + Layers: Control.LayersStatic; + Scale: Control.ScaleStatic; + } + export var Control: ControlStatic; + + export interface Control extends IControl { + /** + * Sets the position of the control. See control positions. + */ + setPosition(position: PositionString): Control; + + /** + * Returns the current position of the control. + */ + getPosition(): PositionString; + + /** + * Adds the control to the map. + */ + addTo(map: Map): Control; + + /** + * Removes the control from the map. + */ + removeFrom(map: Map): Control; + + /** + * Returns the HTML container of the control. + */ + getContainer(): HTMLElement; + + // IControl members + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } + + namespace Control { + export interface ZoomStatic extends ClassStatic { + /** + * Creates a zoom control. + */ + new (options?: ZoomOptions): Zoom; + } + + export interface Zoom extends L.Control { + } + + export interface ZoomOptions { + /** + * The position of the control (one of the map corners). + * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. + * + * Default value: 'topright'. + */ + position?: PositionString; + + /** + * The text set on the zoom in button. + * + * Default value: '+' + */ + zoomInText?: string; + + /** + * The text set on the zoom out button. + * + * Default value: '-' + */ + zoomOutText?: string; + + /** + * The title set on the zoom in button. + * + * Default value: 'Zoom in' + */ + zoomInTitle?: string; + + /** + * The title set on the zoom out button. + * + * Default value: 'Zoom out' + */ + zoomOutTitle?: string; + } + + export interface AttributionStatic extends ClassStatic { + /** + * Creates an attribution control. + */ + new(options?: AttributionOptions): Attribution; + } + + export interface Attribution extends L.Control { + /** + * Sets the text before the attributions. + */ + setPrefix(prefix: string): Attribution; + + /** + * Adds an attribution text (e.g. 'Vector data © CloudMade'). + */ + addAttribution(text: string): Attribution; + + /** + * Removes an attribution text. + */ + removeAttribution(text: string): Attribution; + + } + + export interface LayersStatic extends ClassStatic { + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; + } + + export interface Layers extends L.Control, IEventPowered { + /** + * Adds a base layer (radio button entry) with the given name to the control. + */ + addBaseLayer(layer: ILayer, name: string): Layers; + + /** + * Adds an overlay (checkbox entry) with the given name to the control. + */ + addOverlay(layer: ILayer, name: string): Layers; + + /** + * Remove the given layer from the control. + */ + removeLayer(layer: ILayer): Layers; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Layers; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + fire(type: string, data?: any): Layers; + addEventListener(eventMap: any, context?: any): Layers; + removeEventListener(eventMap?: any, context?: any): Layers; + clearAllEventListeners(): Layers; + on(eventMap: any, context?: any): Layers; + off(eventMap?: any, context?: any): Layers; + } + + export interface ScaleStatic extends ClassStatic { + /** + * Creates an scale control with the given options. + */ + new(options?: ScaleOptions): Scale; + } + + export interface Scale extends L.Control { + } + } + + export interface control { + /** + * Creates a control with the given options. + */ + (options?: ControlOptions): Control; + } + + export namespace control { + + /** + * Creates a zoom control. + */ + export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; + + /** + * Creates an attribution control. + */ + export function attribution(options?: AttributionOptions): L.Control.Attribution; + + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; + + /** + * Creates an scale control with the given options. + */ + export function scale(options?: ScaleOptions): L.Control.Scale; + } +} + +declare namespace L { + + export interface ControlOptions { + + /** + * The initial position of the control (one of the map corners). See control + * positions. + * Default value: 'topright'. + */ + position?: PositionString; + + } +} + +declare namespace L { + + namespace CRS { + + /** + * The most common CRS for online maps, used by almost all free and commercial + * tile providers. Uses Spherical Mercator projection. Set in by default in + * Map's crs option. + */ + export var EPSG3857: ICRS; + + /** + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. + */ + export var EPSG4326: ICRS; + + /** + * Rarely used by some commercial tile providers. Uses Elliptical Mercator + * projection. + */ + export var EPSG3395: ICRS; + + /** + * A simple CRS that maps longitude and latitude into x and y directly. May be + * used for maps of flat surfaces (e.g. game maps). Note that the y axis should + * still be inverted (going from bottom to top). + */ + export var Simple: ICRS; + + } +} + +declare namespace L { + + /** + * Creates a div icon instance with the given options. + */ + function divIcon(options: DivIconOptions): DivIcon; + + export interface DivIconStatic extends ClassStatic { + /** + * Creates a div icon instance with the given options. + */ + new(options: DivIconOptions): DivIcon; + } + export var DivIcon: DivIconStatic; + + export interface DivIcon extends Icon { + } +} + +declare namespace L { + + export interface DivIconOptions { + + /** + * Size of the icon in pixels. Can be also set through CSS. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to the icon. + * + * Default value: 'leaflet-div-icon'. + */ + className?: string; + + /** + * A custom HTML code to put inside the div element. + * + * Default value: ''. + */ + html?: string; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + } +} + +declare namespace L { + + export interface DomEvent { + + /** + * Adds a listener fn to the element's DOM event of the specified type. this keyword + * inside the listener will point to context, or to the element if not specified. + */ + addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Removes an event listener from the element. + */ + removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Stop the given event from propagation to parent elements. Used inside the + * listener functions: + * L.DomEvent.addListener(div, 'click', function + * (e) { + * L.DomEvent.stopPropagation(e); + * }); + */ + stopPropagation(e: Event): DomEvent; + + /** + * Prevents the default action of the event from happening (such as following + * a link in the href of the a element, or doing a POST request with page reload + * when form is submitted). Use it inside listener functions. + */ + preventDefault(e: Event): DomEvent; + + /** + * Does stopPropagation and preventDefault at the same time. + */ + stop(e: Event): DomEvent; + + /** + * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' + * and 'touchstart' events. + */ + disableClickPropagation(el: HTMLElement): DomEvent; + + /** + * Gets normalized mouse position from a DOM event relative to the container + * or to the whole page if not specified. + */ + getMousePosition(e: Event, container?: HTMLElement): Point; + + /** + * Gets normalized wheel delta from a mousewheel DOM event. + */ + getWheelDelta(e: Event): number; + + } + + export var DomEvent: DomEvent; +} + +declare namespace L { + + namespace DomUtil { + + /** + * Returns an element with the given id if a string was passed, or just returns + * the element if it was passed directly. + */ + export function get(id: string): HTMLElement; + + /** + * Returns the value for a certain style attribute on an element, including + * computed values or values set through CSS. + */ + export function getStyle(el: HTMLElement, style: string): string; + + /** + * Returns the offset to the viewport for the requested element. + */ + export function getViewportOffset(el: HTMLElement): Point; + + /** + * Creates an element with tagName, sets the className, and optionally appends + * it to container element. + */ + export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; + + /** + * Makes sure text cannot be selected, for example during dragging. + */ + export function disableTextSelection(): void; + + /** + * Makes text selection possible again. + */ + export function enableTextSelection(): void; + + /** + * Returns true if the element class attribute contains name. + */ + export function hasClass(el: HTMLElement, name: string): boolean; + + /** + * Adds name to the element's class attribute. + */ + export function addClass(el: HTMLElement, name: string): void; + + /** + * Removes name from the element's class attribute. + */ + export function removeClass(el: HTMLElement, name: string): void; + + /** + * Set the opacity of an element (including old IE support). Value must be from + * 0 to 1. + */ + export function setOpacity(el: HTMLElement, value: number): void; + + /** + * Goes through the array of style names and returns the first name that is a valid + * style name for an element. If no such name is found, it returns false. Useful + * for vendor-prefixed styles like transform. + */ + export function testProp(props: string[]): any; + + /** + * Returns a CSS transform string to move an element by the offset provided in + * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms + * and 2D on other browsers. + */ + export function getTranslateString(point: Point): string; + + /** + * Returns a CSS transform string to scale an element (with the given scale origin). + */ + export function getScaleString(scale: number, origin: Point): string; + + /** + * Sets the position of an element to coordinates specified by point, using + * CSS translate or top/left positioning depending on the browser (used by + * Leaflet internally to position its layers). Forces top/left positioning + * if disable3D is true. + */ + export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; + + /** + * Returns the coordinates of an element previously positioned with setPosition. + */ + export function getPosition(el: HTMLElement): Point; + + /** + * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). + */ + export var TRANSITION: string; + + /** + * Vendor-prefixed transform style name. + */ + export var TRANSFORM: string; + + } +} + +declare namespace L { + export interface DraggableStatic extends ClassStatic { + /** + * Creates a Draggable object for moving the given element when you start dragging + * the dragHandle element (equals the element itself by default). + */ + new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; + } + export var Draggable: DraggableStatic; + + + export interface Draggable extends IEventPowered { + /** + * Enables the dragging ability. + */ + enable(): void; + + /** + * Disables the dragging ability. + */ + disable(): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Draggable; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + fire(type: string, data?: any): Draggable; + addEventListener(eventMap: any, context?: any): Draggable; + removeEventListener(eventMap?: any, context?: any): Draggable; + clearAllEventListeners(): Draggable; + on(eventMap: any, context?: any): Draggable; + off(eventMap?: any, context?: any): Draggable; + } +} + + + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function featureGroup(layers?: T[]): FeatureGroup; + + + export interface FeatureGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): FeatureGroup; + } + export var FeatureGroup: FeatureGroupStatic; + + export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { + /** + * Binds a popup with a particular HTML content to a click on any layer from the + * group that has a bindPopup method. + */ + bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; + + /** + * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates + * of its children). + */ + getBounds(): LatLngBounds; + + /** + * Sets the given path options to each layer of the group that has a setStyle method. + */ + setStyle(style: PathOptions): FeatureGroup; + + /** + * Brings the layer group to the top of all other layers. + */ + bringToFront(): FeatureGroup; + + /** + * Brings the layer group to the bottom of all other layers. + */ + bringToBack(): FeatureGroup; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): FeatureGroup; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + fire(type: string, data?: any): FeatureGroup; + addEventListener(eventMap: any, context?: any): FeatureGroup; + removeEventListener(eventMap?: any, context?: any): FeatureGroup; + clearAllEventListeners(): FeatureGroup; + on(eventMap: any, context?: any): FeatureGroup; + off(eventMap?: any, context?: any): FeatureGroup; + } +} + +declare namespace L { + + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + export interface GeoJSONStatic extends ClassStatic { + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + new(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + /** + * Creates a layer from a given GeoJSON feature. + */ + geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; + + /** + * Creates a LatLng object from an array of 2 numbers (latitude, longitude) + * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted + * as (longitude, latitude). + */ + coordsToLatLng(coords: number[], reverse?: boolean): LatLng; + + /** + * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates + * array. levelsDeep specifies the nesting level (0 is for an array of points, + * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to + * true, the numbers will be interpreted as (longitude, latitude). + */ + coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; + } + export var GeoJSON: GeoJSONStatic; + + export interface GeoJSON extends FeatureGroup { + /** + * Adds a GeoJSON object to the layer. + */ + addData(data: any): boolean; + + /** + * Changes styles of GeoJSON vector layers with the given style function. + */ + setStyle(style: (featureData: any) => any): GeoJSON; + + /** + * Changes styles of GeoJSON vector layers with the given style options. + */ + setStyle(style: PathOptions): GeoJSON; + + /** + * Resets the the given vector layer's style to the original GeoJSON style, + * useful for resetting style after hover events. + */ + resetStyle(layer: Path): GeoJSON; + } +} + +declare namespace L { + export interface GeoJSONOptions { + /** + * Function that will be used for creating layers for GeoJSON points (if not + * specified, simple markers will be created). + */ + pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; + + /** + * Function that will be used to get style options for vector layers created + * for GeoJSON features. + */ + style?: (featureData: any) => any; + + /** + * Function that will be called on each created feature layer. Useful for attaching + * events and popups to features. + */ + onEachFeature?: (featureData: any, layer: ILayer) => void; + + /** + * Function that will be used to decide whether to show a feature or not. + */ + filter?: (featureData: any, layer: ILayer) => boolean; + + /** + * Function that will be used for converting GeoJSON coordinates to LatLng points + * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] + * values in degrees). + */ + coordsToLatLng?: (coords: any[]) => LatLng[]; + } +} + + + + +declare namespace L { + + /** + * Creates an icon instance with the given options. + */ + function icon(options: IconOptions): Icon; + + export interface IconStatic extends ClassStatic { + /** + * Creates an icon instance with the given options. + */ + new(options: IconOptions): Icon; + + Default: { + /** + * Creates a default icon instance with the given options. + */ + new(options?: IconOptions): Icon.Default; + + imagePath: string; + }; + } + export var Icon: IconStatic; + + export interface Icon { + } + + namespace Icon { + /** + * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses + * for markers by default. + */ + export interface Default extends Icon { + } + } +} + +declare namespace L { + + export interface IconOptions { + + /** + * (required) The URL to the icon image (absolute or relative to your script + * path). + */ + iconUrl?: string; + + /** + * The URL to a retina sized version of the icon image (absolute or relative to + * your script path). Used for Retina screen devices. + */ + iconRetinaUrl?: string; + + /** + * Size of the icon image in pixels. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * The URL to the icon shadow image. If not specified, no shadow image will be + * created. + */ + shadowUrl?: string; + + /** + * The URL to the retina sized version of the icon shadow image. If not specified, + * no shadow image will be created. Used for Retina screen devices. + */ + shadowRetinaUrl?: string; + + /** + * Size of the shadow image in pixels. + */ + shadowSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the shadow (relative to its top left corner) + * (the same as iconAnchor if not specified). + */ + shadowAnchor?: Point|[number, number]; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to both icon and shadow images. Empty by default. + */ + className?: string; + } +} + +declare namespace L { + + export interface IControl { + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ICRS { + + /** + * Projection that this CRS uses. + */ + projection: IProjection; + + /** + * Transformation that this CRS uses to turn projected coordinates into screen + * coordinates for a particular tile service. + */ + transformation: Transformation; + + /** + * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). + */ + code: string; + + /** + * Projects geographical coordinates on a given zoom into pixel coordinates. + */ + latLngToPoint(latlng: LatLng, zoom: number): Point; + + /** + * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom + * into geographical coordinates. + */ + pointToLatLng(point: Point, zoom: number): LatLng; + + /** + * Projects geographical coordinates into coordinates in units accepted + * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). + */ + project(latlng: LatLng): Point; + + /** + * Returns the scale used when transforming projected coordinates into pixel + * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for + * Mercator-based CRS. + */ + scale(zoom: number): number; + + /** + * Returns the size of the world in pixels for a particular zoom. + */ + getSize(zoom: number): Point; + + } +} + +declare namespace L { + + export interface IEventPowered { + + /** + * Adds a listener function (fn) to a particular event type of the object. You + * can optionally specify the context of the listener (object the this keyword + * will point to). You can also pass several space-separated types (e.g. 'click + * dblclick'). + */ + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * The same as above except the listener will only get fired once and then removed. + */ + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + /** + * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} + */ + addEventListener(eventMap: any, context?: any): T; + + /** + * Removes a previously added listener function. If no function is specified, + * it will remove all the listeners of that particular event from the object. + */ + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Removes a set of type/listener pairs. + */ + removeEventListener(eventMap?: any, context?: any): T; + + /** + * Returns true if a particular event type has some listeners attached to it. + */ + hasEventListeners(type: string): boolean; + + /** + * Fires an event of the specified type. You can optionally provide an data object + * — the first argument of the listener function will contain its properties. + */ + fireEvent(type: string, data?: any): T; + + /** + * Removes all listeners to all events on the object. + */ + clearAllEventListeners(): T; + + /** + * Alias to addEventListener. + */ + on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to addEventListener. + */ + on(eventMap: any, context?: any): T; + + /** + * Alias to addOneTimeEventListener. + */ + once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(eventMap?: any, context?: any): T; + + /** + * Alias to fireEvent. + */ + fire(type: string, data?: any): T; + } +} + +declare namespace L { + + export interface IHandler { + + /** + * Enables the handler. + */ + enable(): void; + + /** + * Disables the handler. + */ + disable(): void; + + /** + * Returns true if the handler is enabled. + */ + enabled(): boolean; + } + + export interface Handler { + initialize(map: Map): void; + } +} + +declare namespace L { + + export interface ILayer { + + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + namespace Mixin { + export interface LeafletMixinEvents extends IEventPowered { + } + + export var Events: LeafletMixinEvents; + } +} + +declare namespace L { + + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + + export interface ImageOverlayStatic extends ClassStatic { + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + } + export var ImageOverlay: ImageOverlayStatic; + + export interface ImageOverlay extends ILayer { + /** + * Adds the overlay to the map. + */ + addTo(map: Map): ImageOverlay; + + /** + * Sets the opacity of the overlay. + */ + setOpacity(opacity: number): ImageOverlay; + + /** + * Changes the URL of the image. + */ + setUrl(imageUrl: string): ImageOverlay; + + /** + * Brings the layer to the top of all overlays. + */ + bringToFront(): ImageOverlay; + + /** + * Brings the layer to the bottom of all overlays. + */ + bringToBack(): ImageOverlay; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ImageOverlayOptions { + + /** + * The opacity of the image overlay. + */ + opacity?: number; + } +} + +declare namespace L { + + export interface IProjection { + + /** + * Projects geographical coordinates into a 2D point. + */ + project(latlng: LatLng): Point; + + /** + * The inverse of project. Projects a 2D point into geographical location. + */ + unproject(point: Point): LatLng; + } +} + +declare namespace L { + + /** + * A constant that represents the Leaflet version in use. + */ + export var version: string; + + /** + * This method restores the L global variale to the original value it had + * before Leaflet inclusion, and returns the real Leaflet namespace. + */ + export function noConflict(): typeof L; +} + +declare namespace L { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(coords: LatLngExpression): LatLng; + + export interface LatLngStatic { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(coords: LatLngExpression): LatLng; + + /** + * A multiplier for converting degrees into radians. + * + * Value: Math.PI / 180. + */ + DEG_TO_RAD: number; + + /** + * A multiplier for converting radians into degrees. + * + * Value: 180 / Math.PI. + */ + RAD_TO_DEG: number; + + /** + * Max margin of error for the equality check. + * + * Value: 1.0E-9. + */ + MAX_MARGIN: number; + } + export var LatLng: LatLngStatic; + + export interface LatLng { + /** + * Returns the distance (in meters) to the given LatLng calculated using the + * Haversine formula. See description on wikipedia + */ + distanceTo(otherLatlng: LatLngExpression): number; + + /** + * Returns true if the given LatLng point is at the same position (within a small + * margin of error). + */ + equals(otherLatlng: LatLngExpression): boolean; + + /** + * Returns a string representation of the point (for debugging purposes). + */ + toString(): string; + + /** + * Returns a new LatLng object with the longitude wrapped around left and right + * boundaries (-180 to 180 by default). + */ + wrap(left?: number, right?: number): LatLng; + + /** + * Latitude in degrees. + */ + lat: number; + + /** + * Longitude in degrees. + */ + lng: number; + } +} + +declare namespace L { + + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + + export interface LatLngBoundsStatic { + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + new(latlngs: LatLngBoundsExpression): LatLngBounds; + } + export var LatLngBounds: LatLngBoundsStatic; + + export interface LatLngBounds { + /** + * Extends the bounds to contain the given point. + */ + extend(latlng: LatLngExpression): LatLngBounds; + + /** + * Extends the bounds to contain the given bounds. + */ + extend(latlng: LatLngBoundsExpression): LatLngBounds; + + /** + * Returns the south-west point of the bounds. + */ + getSouthWest(): LatLng; + + /** + * Returns the north-east point of the bounds. + */ + getNorthEast(): LatLng; + + /** + * Returns the north-west point of the bounds. + */ + getNorthWest(): LatLng; + + /** + * Returns the south-east point of the bounds. + */ + getSouthEast(): LatLng; + + /** + * Returns the west longitude in degrees of the bounds. + */ + getWest(): number; + + /** + * Returns the east longitude in degrees of the bounds. + */ + getEast(): number; + + /** + * Returns the north latitude in degrees of the bounds. + */ + getNorth(): number; + + /** + * Returns the south latitude in degrees of the bounds. + */ + getSouth(): number; + + /** + * Returns the center point of the bounds. + */ + getCenter(): LatLng; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(latlng: LatLngExpression): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle is equivalent (within a small margin of error) + * to the given bounds. + */ + equals(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' + * format. Useful for sending requests to web services that return geo data. + */ + toBBoxString(): string; + + /** + * Returns bigger bounds created by extending the current bounds by a given + * percentage in each direction. + */ + pad(bufferRatio: number): LatLngBounds; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + } +} + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function layerGroup(layers?: T[]): LayerGroup; + + + export interface LayerGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): LayerGroup; + } + export var LayerGroup: LayerGroupStatic; + + export interface LayerGroup extends ILayer { + /** + * Adds the group of layers to the map. + */ + addTo(map: Map): LayerGroup; + + /** + * Adds a given layer to the group. + */ + addLayer(layer: T): LayerGroup; + + /** + * Removes a given layer from the group. + */ + removeLayer(layer: T): LayerGroup; + + /** + * Removes a given layer of the given id from the group. + */ + removeLayer(id: string): LayerGroup; + + /** + * Returns true if the given layer is currently added to the group. + */ + hasLayer(layer: T): boolean; + + /** + * Returns the layer with the given id. + */ + getLayer(id: string): T; + + /** + * Returns an array of all the layers added to the group. + */ + getLayers(): T[]; + + /** + * Removes all the layers from the group. + */ + clearLayers(): LayerGroup; + + /** + * Iterates over the layers of the group, optionally specifying context of + * the iterator function. + */ + eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; + + /** + * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s + */ + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + + +declare namespace L { + + export interface LayersOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * + * Default value: 'topright'. + */ + position?: PositionString; + + /** + * If true, the control will be collapsed into an icon and expanded on mouse hover + * or touch. + * + * Default value: true. + */ + collapsed?: boolean; + + /** + * If true, the control will assign zIndexes in increasing order to all of its + * layers so that the order is preserved when switching them on/off. + * + * Default value: true. + */ + autoZIndex?: boolean; + + } +} + +declare namespace L { + + export interface LeafletErrorEvent extends LeafletEvent { + + /** + * Error message. + */ + message: string; + + /** + * Error code (if applicable). + */ + code: number; + } +} + +declare namespace L { + + export interface LeafletEvent { + + /** + * The event type (e.g. 'click'). + */ + type: string; + + /** + * The object that fired the event. + */ + target: any; + } +} + +declare namespace L { + + export interface LeafletGeoJSONEvent extends LeafletEvent { + + /** + * The layer for the GeoJSON feature that is being added to the map. + */ + layer: ILayer; + + /** + * GeoJSON properties of the feature. + */ + properties: any; + + /** + * GeoJSON geometry type of the feature. + */ + geometryType: string; + + /** + * GeoJSON ID of the feature (if present). + */ + id: string; + } +} + +declare namespace L { + + export interface LeafletLayerEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + } +} + +declare namespace L { + + export interface LeafletLayersControlEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + + /** + * The name of the layer that was added or removed. + */ + name: string; + } +} + +declare namespace L { + + export interface LeafletLocationEvent extends LeafletEvent { + + /** + * Detected geographical location of the user. + */ + latlng: LatLng; + + /** + * Geographical bounds of the area user is located in (with respect to the accuracy + * of location). + */ + bounds: LatLngBounds; + + /** + * Accuracy of location in meters. + */ + accuracy: number; + + /** + * Height of the position above the WGS84 ellipsoid in meters. + */ + altitude: number; + + /** + * Accuracy of altitude in meters. + */ + altitudeAccuracy: number; + + /** + * The direction of travel in degrees counting clockwise from true North. + */ + heading: number; + + /** + * Current velocity in meters per second. + */ + speed: number; + + /** + * The time when the position was acquired. + */ + timestamp: number; + + } +} + +declare namespace L { + + export interface LeafletMouseEvent extends LeafletEvent { + + /** + * The geographical point where the mouse event occured. + */ + latlng: LatLng; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map layer. + */ + layerPoint: Point; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map сontainer. + */ + containerPoint: Point; + + /** + * The original DOM mouse event fired by the browser. + */ + originalEvent: MouseEvent; + } +} + +declare namespace L { + + export interface LeafletPopupEvent extends LeafletEvent { + + /** + * The popup that was opened or closed. + */ + popup: Popup; + } +} + +declare namespace L { + + export interface LeafletDragEndEvent extends LeafletEvent { + + /** + * The distance in pixels the draggable element was moved by. + */ + distance: number; + } +} + +declare namespace L { + + export interface LeafletResizeEvent extends LeafletEvent { + + /** + * The old size before resize event. + */ + oldSize: Point; + + /** + * The new size after the resize event. + */ + newSize: Point; + } +} + +declare namespace L { + + export interface LeafletTileEvent extends LeafletEvent { + + /** + * The tile element (image). + */ + tile: HTMLElement; + + /** + * The source URL of the tile. + */ + url: string; + } +} + +declare namespace L { + + namespace LineUtil { + + /** + * Dramatically reduces the number of points in a polyline while retaining + * its shape and returns a new array of simplified points. Used for a huge performance + * boost when processing/displaying Leaflet polylines for each zoom level + * and also reducing visual noise. tolerance affects the amount of simplification + * (lesser value means higher quality but slower and with more points). Also + * released as a separated micro-library Simplify.js. + */ + export function simplify(points: Point[], tolerance: number): Point[]; + + /** + * Returns the distance between point p and segment p1 to p2. + */ + export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; + + /** + * Returns the closest point from a point p on a segment p1 to p2. + */ + export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; + + /** + * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show + * polyline points that are on the screen or near, increasing performance. Returns + * either false or a length-2 array of clipped points. + */ + export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; + + } +} + +declare namespace L { + + export interface LocateOptions { + + /** + * If true, starts continous watching of location changes (instead of detecting + * it once) using W3C watchPosition method. You can later stop watching using + * map.stopLocate() method. + * + * Default value: false. + */ + watch?: boolean; + + /** + * If true, automatically sets the map view to the user location with respect + * to detection accuracy, or to world view if geolocation failed. + * + * Default value: false. + */ + setView?: boolean; + + /** + * The maximum zoom for automatic view setting when using `setView` option. + * + * Default value: Infinity. + */ + maxZoom?: number; + + /** + * Number of millisecond to wait for a response from geolocation before firing + * a locationerror event. + * + * Default value: 10000. + */ + timeout?: number; + + /** + * Maximum age of detected location. If less than this amount of milliseconds + * passed since last geolocation response, locate will return a cached location. + * + * Default value: 0. + */ + maximumAge?: number; + + /** + * Enables high accuracy, see description in the W3C spec. + * + * Default value: false. + */ + enableHighAccuracy?: boolean; + } +} + +declare namespace L { + + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + */ + function map(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + */ + function map(id: string, options?: Map.MapOptions): Map; + + + export interface MapStatic extends ClassStatic { + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: string, options?: Map.MapOptions): Map; + } + export var Map: MapStatic; + + export interface Map extends IEventPowered { + // Methods for Modifying Map State + + /** + * Sets the view of the map (geographical center and zoom) with the given + * animation options. + */ + setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets the zoom of the map. + */ + setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Increases the zoom of the map by delta (1 by default). + */ + zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Decreases the zoom of the map by delta (1 by default). + */ + zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Zooms the map while keeping a specified point on the map stationary + * (e.g. used internally for scroll zoom and double-click zoom). + */ + setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets a map view that contains the given geographical bounds with the maximum + * zoom level possible. + */ + fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; + + /** + * Sets a map view that mostly contains the whole world with the maximum zoom + * level possible. + */ + fitWorld(options?: Map.FitBoundsOptions): Map; + + /** + * Pans the map to a given center. Makes an animated pan if new center is not more + * than one screen away from the current one. + */ + panTo(latlng: LatLngExpression, options?: PanOptions): Map; + + /** + * Pans the map to the closest view that would lie inside the given bounds (if + * it's not already). + */ + panInsideBounds(bounds: LatLngBounds): Map; + + /** + * Pans the map by a given number of pixels (animated). + */ + panBy(point: Point, options?: PanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + * If options.pan is false, panning will not occur. + */ + invalidateSize(options: Map.ZoomPanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + */ + invalidateSize(animate: boolean): Map; + + /** + * Restricts the map view to the given bounds (see map maxBounds option), + * passing the given animation options through to `setView`, if required. + */ + setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; + + /** + * Tries to locate the user using Geolocation API, firing locationfound event + * with location data on success or locationerror event on failure, and optionally + * sets the map view to the user location with respect to detection accuracy + * (or to the world view if geolocation failed). See Locate options for more + * details. + */ + locate(options?: LocateOptions): Map; + + /** + * Stops watching location previously initiated by map.locate({watch: true}) + * and aborts resetting the map view if map.locate was called with {setView: true}. + */ + stopLocate(): Map; + + /** + * Destroys the map and clears all related event listeners. + */ + remove(): Map; + + // Methods for Getting Map State + + /** + * Returns the geographical center of the map view. + */ + getCenter(): LatLng; + + /** + * Returns the current zoom of the map view. + */ + getZoom(): number; + + /** + * Returns the minimum zoom level of the map. + */ + getMinZoom(): number; + + /** + * Returns the maximum zoom level of the map. + */ + getMaxZoom(): number; + + /** + * Returns the LatLngBounds of the current map view. + */ + getBounds(): LatLngBounds; + + /** + * Returns the maximum zoom level on which the given bounds fit to the map view + * in its entirety. If inside (optional) is set to true, the method instead returns + * the minimum zoom level on which the map view fits into the given bounds in its + * entirety. + */ + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + + /** + * Returns the current size of the map container. + */ + getSize(): Point; + + /** + * Returns the bounds of the current map view in projected pixel coordinates + * (sometimes useful in layer and overlay implementations). + */ + getPixelBounds(): Bounds; + + /** + * Returns the projected pixel coordinates of the top left point of the map layer + * (useful in custom layer and overlay implementations). + */ + getPixelOrigin(): Point; + + // Methods for Layers and Controls + + /** + * Adds the given layer to the map. If optional insertAtTheBottom is set to true, + * the layer is inserted under all others (useful when switching base tile layers). + */ + addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; + + /** + * Removes the given layer from the map. + */ + removeLayer(layer: ILayer): Map; + + /** + * Returns true if the given layer is currently added to the map. + */ + hasLayer(layer: ILayer): boolean; + + /** + * Opens the specified popup while closing the previously opened (to make sure + * only one is opened at one time for usability). + */ + openPopup(popup: Popup): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Closes the popup previously opened with openPopup (or the given one). + */ + closePopup(popup?: Popup): Map; + + /** + * Adds the given control to the map. + */ + addControl(control: IControl): Map; + + /** + * Removes the given control from the map. + */ + removeControl(control: IControl): Map; + + // Conversion Methods + + /** + * Returns the map layer point that corresponds to the given geographical coordinates + * (useful for placing overlays on the map). + */ + latLngToLayerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map layer point. + */ + layerPointToLatLng(point: Point): LatLng; + + /** + * Converts the point relative to the map container to a point relative to the + * map layer. + */ + containerPointToLayerPoint(point: Point): Point; + + /** + * Converts the point relative to the map layer to a point relative to the map + * container. + */ + layerPointToContainerPoint(point: Point): Point; + + /** + * Returns the map container point that corresponds to the given geographical + * coordinates. + */ + latLngToContainerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map container point. + */ + containerPointToLatLng(point: Point): LatLng; + + /** + * Projects the given geographical coordinates to absolute pixel coordinates + * for the given zoom level (current zoom level by default). + */ + project(latlng: LatLngExpression, zoom?: number): Point; + + /** + * Projects the given absolute pixel coordinates to geographical coordinates + * for the given zoom level (current zoom level by default). + */ + unproject(point: Point, zoom?: number): LatLng; + + /** + * Returns the pixel coordinates of a mouse click (relative to the top left corner + * of the map) given its event object. + */ + mouseEventToContainerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the pixel coordinates of a mouse click relative to the map layer given + * its event object. + */ + mouseEventToLayerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the geographical coordinates of the point the mouse clicked on given + * the click's event object. + */ + mouseEventToLatLng(event: LeafletMouseEvent): LatLng; + + // Other Methods + + /** + * Returns the container element of the map. + */ + getContainer(): HTMLElement; + + /** + * Returns an object with different map panes (to render overlays in). + */ + getPanes(): MapPanes; + + // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? + /** + * Runs the given callback when the map gets initialized with a place and zoom, + * or immediately if it happened already, optionally passing a function context. + */ + whenReady(fn: (map: Map) => void, context?: any): Map; + + // Properties + + /** + * Map dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + /** + * Touch zoom handler. + */ + touchZoom: IHandler; + + /** + * Double click zoom handler. + */ + doubleClickZoom: IHandler; + + /** + * Scroll wheel zoom handler. + */ + scrollWheelZoom: IHandler; + + /** + * Box (shift-drag with mouse) zoom handler. + */ + boxZoom: IHandler; + + /** + * Keyboard navigation handler. + */ + keyboard: IHandler; + + /** + * Mobile touch hacks (quick tap and touch hold) handler. + */ + tap: IHandler; + + /** + * Zoom control. + */ + zoomControl: Control.Zoom; + + /** + * Attribution control. + */ + attributionControl: Control.Attribution; + + /** + * Map state options + */ + options: Map.MapOptions; + + /** + * Iterates over the layers of the map, optionally specifying context + * of the iterator function. + */ + eachLayer(fn: (layer: ILayer) => void, context?: any): Map; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Map; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; + removeEventListener(eventMap?: any, context?: any): Map; + clearAllEventListeners(): Map; + on(eventMap: any, context?: any): Map; + off(eventMap?: any, context?: any): Map; + } +} + +declare namespace L.Map { + + export interface MapOptions { + + // Map State Options + + /** + * Initial geographical center of the map. + */ + center?: LatLng; + + /** + * Initial map zoom. + */ + zoom?: number; + + /** + * Layers that will be added to the map initially. + */ + layers?: ILayer[]; + + /** + * Minimum zoom level of the map. Overrides any minZoom set on map layers. + */ + minZoom?: number; + + /** + * Maximum zoom level of the map. This overrides any maxZoom set on map layers. + */ + maxZoom?: number; + + /** + * When this option is set, the map restricts the view to the given geographical + * bounds, bouncing the user back when he tries to pan outside the view, and also + * not allowing to zoom out to a view that's larger than the given bounds (depending + * on the map size). To set the restriction dynamically, use setMaxBounds method + */ + maxBounds?: LatLngBounds; + + /** + * Coordinate Reference System to use. Don't change this if you're not sure + * what it means. + * + * Default value: L.CRS.EPSG3857. + */ + crs?: ICRS; + + // Interaction Options + + /** + * Whether the map be draggable with mouse/touch or not. + * + * Default value: true. + */ + dragging?: boolean; + + /** + * Whether the map can be zoomed by touch-dragging with two fingers. + * + * Default value: true. + */ + touchZoom?: boolean; + + /** + * Whether the map can be zoomed by using the mouse wheel. + * If passed 'center', it will zoom to the center of the view regardless of + * where the mouse was. + * + * Default value: true. + */ + scrollWheelZoom?: boolean; + + /** + * Whether the map can be zoomed in by double clicking on it and zoomed out + * by double clicking while holding shift. + * If passed 'center', double-click zoom will zoom to the center of the view + * regardless of where the mouse was. + * + * Default value: true. + */ + doubleClickZoom?: boolean; + + /** + * Whether the map can be zoomed to a rectangular area specified by dragging + * the mouse while pressing shift. + * + * Default value: true. + */ + boxZoom?: boolean; + + /** + * Enables mobile hacks for supporting instant taps (fixing 200ms click delay + * on iOS/Android) and touch holds (fired as contextmenu events). + * + * Default value: true. + */ + tap?: boolean; + + /** + * The max number of pixels a user can shift his finger during touch for it + * to be considered a valid tap. + * + * Default value: 15. + */ + tapTolerance?: number; + + /** + * Whether the map automatically handles browser window resize to update itself. + * + * Default value: true. + */ + trackResize?: boolean; + + /** + * With this option enabled, the map tracks when you pan to another "copy" of + * the world and seamlessly jumps to the original one so that all overlays like + * markers and vector layers are still visible. + * + * Default value: false. + */ + worldCopyJump?: boolean; + + /** + * Set it to false if you don't want popups to close when user clicks the map. + * + * Default value: true. + */ + closePopupOnClick?: boolean; + + // Keyboard Navigation Options + + /** + * Makes the map focusable and allows users to navigate the map with keyboard + * arrows and +/- keys. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Amount of pixels to pan when pressing an arrow key. + * + * Default value: 80. + */ + keyboardPanOffset?: number; + + /** + * Number of zoom levels to change when pressing + or - key. + * + * Default value: 1. + */ + keyboardZoomOffset?: number; + + // Panning Inertia Options + + /** + * If enabled, panning of the map will have an inertia effect where the map builds + * momentum while dragging and continues moving in the same direction for some + * time. Feels especially nice on touch devices. + * + * Default value: true. + */ + inertia?: boolean; + + /** + * The rate with which the inertial movement slows down, in pixels/second2. + * + * Default value: 3000. + */ + inertiaDeceleration?: number; + + /** + * Max speed of the inertial movement, in pixels/second. + * + * Default value: 1500. + */ + inertiaMaxSpeed?: number; + + /** + * Amount of milliseconds that should pass between stopping the movement and + * releasing the mouse or touch to prevent inertial movement. + * + * Default value: 32 for touch devices and 14 for the rest. + */ + inertiaThreshold?: number; + + // Control options + + /** + * Whether the zoom control is added to the map by default. + * + * Default value: true. + */ + zoomControl?: boolean; + + /** + * Whether the attribution control is added to the map by default. + * + * Default value: true. + */ + attributionControl?: boolean; + + // Animation options + + /** + * Whether the tile fade animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + fadeAnimation?: boolean; + + /** + * Whether the tile zoom animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + zoomAnimation?: boolean; + + /** + * Won't animate zoom if the zoom difference exceeds this value. + * + * Default value: 4. + */ + zoomAnimationThreshold?: number; + + /** + * Whether markers animate their zoom with the zoom animation, if disabled + * they will disappear for the length of the animation. By default it's enabled + * in all browsers that support CSS3 Transitions except Android. + */ + markerZoomAnimation?: boolean; + + /** + * Set it to false if you don't want the map to zoom beyond min/max zoom + * and then bounce back when pinch-zooming. + * + * Default value: true. + */ + bounceAtZoomLimits?: boolean; + } + + export interface ZoomOptions { + /** + * If not specified, zoom animation will happen if the zoom origin is inside the current view. + * If true, the map will attempt animating zoom disregarding where zoom origin is. + * Setting false will make it always reset the view completely without animation. + */ + animate?: boolean; + } + + export interface ZoomPanOptions { + + /** + * If true, the map view will be completely reset (without any animations). + * + * Default value: false. + */ + reset?: boolean; + + /** + * Sets the options for the panning (without the zoom change) if it occurs. + */ + pan?: PanOptions; + + /** + * Sets the options for the zoom change if it occurs. + */ + zoom?: ZoomOptions; + + /** + * An equivalent of passing animate to both zoom and pan options (see below). + */ + animate?: boolean; + + /** + * If true, it will delay moveend event so that it doesn't happen many times in a row. + */ + debounceMoveend?: boolean; + + /** + * Duration of animated panning, in seconds. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). + * 1.0 means linear animation, the less the more bowed the curve. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + */ + noMoveStart?: boolean; + } + + export interface FitBoundsOptions extends ZoomPanOptions { + + /** + * Sets the amount of padding in the top left corner of a map container that + * shouldn't be accounted for when setting the view to fit bounds. Useful if + * you have some control overlays on the map like a sidebar and you don't + * want them to obscure objects you're zooming to. + * + * Default value: [0, 0]. + */ + paddingTopLeft?: Point; + + /** + * The same for bottom right corner of the map. + * + * Default value: [0, 0]. + */ + paddingBottomRight?: Point; + + /** + * Equivalent of setting both top left and bottom right padding to the same value. + * + * Default value: [0, 0]. + */ + padding?: Point; + + /** + * The maximum possible zoom to use. + * + * Default value: null + */ + maxZoom?: number; + } +} + +declare namespace L { + + export interface MapPanes { + + /** + * Pane that contains all other map panes. + */ + mapPane: HTMLElement; + + /** + * Pane for tile layers. + */ + tilePane: HTMLElement; + + /** + * Pane that contains all the panes except tile pane. + */ + objectsPane: HTMLElement; + + /** + * Pane for overlay shadows (e.g. marker shadows). + */ + shadowPane: HTMLElement; + + /** + * Pane for overlays like polylines and polygons. + */ + overlayPane: HTMLElement; + + /** + * Pane for marker icons. + */ + markerPane: HTMLElement; + + /** + * Pane for popups. + */ + popupPane: HTMLElement; + } +} + +declare namespace L { + + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; + + var Marker: { + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + new(latlng: LatLngExpression, options?: MarkerOptions): Marker; + }; + + export interface Marker extends ILayer, IEventPowered { + /** + * Adds the marker to the map. + */ + addTo(map: Map): Marker; + + /** + * Returns the current geographical position of the marker. + */ + getLatLng(): LatLng; + + /** + * Changes the marker position to the given point. + */ + setLatLng(latlng: LatLngExpression): Marker; + + /** + * Changes the marker icon. + */ + setIcon(icon: Icon): Marker; + + /** + * Changes the zIndex offset of the marker. + */ + setZIndexOffset(offset: number): Marker; + + /** + * Changes the opacity of the marker. + */ + setOpacity(opacity: number): Marker; + + /** + * Updates the marker position, useful if coordinates of its latLng object + * were changed directly. + */ + update(): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(html: string, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(popup: Popup, options?: PopupOptions): Marker; + + /** + * Unbinds the popup previously bound to the marker with bindPopup. + */ + unbindPopup(): Marker; + + /** + * Opens the popup previously bound by the bindPopup method. + */ + openPopup(): Marker; + + /** + * Returns the popup previously bound by the bindPopup method. + */ + getPopup(): Popup; + + /** + * Closes the bound popup of the marker if it's opened. + */ + closePopup(): Marker; + + /** + * Toggles the popup previously bound by the bindPopup method. + */ + togglePopup(): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(html: string, options?: PopupOptions): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). + */ + toGeoJSON(): GeoJSON.Feature; + + /** + * Marker dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Marker; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + fire(type: string, data?: any): Marker; + addEventListener(eventMap: any, context?: any): Marker; + removeEventListener(eventMap?: any, context?: any): Marker; + clearAllEventListeners(): Marker; + on(eventMap: any, context?: any): Marker; + off(eventMap?: any, context?: any): Marker; + } +} + +declare namespace L { + + export interface MarkerOptions { + + /** + * Icon class to use for rendering the marker. See Icon documentation for details + * on how to customize the marker icon. + * + * Default value: new L.Icon.Default(). + */ + icon?: Icon; + + /** + * If false, the marker will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Whether the marker is draggable with mouse/touch or not. + * + * Default value: false. + */ + draggable?: boolean; + + /** + * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Text for the browser tooltip that appear on marker hover (no tooltip by default). + * + * Default value: ''. + */ + title?: string; + + /** + * Text for the alt attribute of the icon image (useful for accessibility). + * + * Default value: ''. + */ + alt?: string; + + /** + * By default, marker images zIndex is set automatically based on its latitude. + * You this option if you want to put the marker on top of all others (or below), + * specifying a high value like 1000 (or high negative value, respectively). + * + * Default value: 0. + */ + zIndexOffset?: number; + + /** + * The opacity of the marker. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * If true, the marker will get on top of others when you hover the mouse over it. + * + * Default value: false. + */ + riseOnHover?: boolean; + + /** + * The z-index offset used for the riseOnHover feature. + * + * Default value: 250. + */ + riseOffset?: number; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + + export interface MultiPolygonStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + } + export var MultiPolygon: MultiPolygonStatic; + + export interface MultiPolygon extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolygon; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolygon; + + /** + * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + + export interface MultiPolylineStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + } + export var MultiPolyline: MultiPolylineStatic; + + export interface MultiPolyline extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolyline; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolyline; + + /** + * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + export interface PanOptions { + + /** + * If true, panning will always be animated if possible. If false, it will not + * animate panning, either resetting the map view if panning more than a screen + * away, or just setting a new offset for the map pane (except for `panBy` + * which always does the latter). + */ + animate?: boolean; + + /** + * Duration of animated panning. + * + * Default value: 0.25. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic + * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. + * + * Default value: 0.25. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + * + * Default value: false. + */ + noMoveStart?: boolean; + } +} + +declare namespace L { + + export interface Path extends ILayer, IEventPowered { + + /** + * Adds the layer to the map. + */ + addTo(map: Map): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(html: string, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(popup: Popup, options?: PopupOptions): Path; + + /** + * Unbinds the popup previously bound to the path with bindPopup. + */ + unbindPopup(): Path; + + /** + * Opens the popup previously bound by the bindPopup method in the given point, + * or in one of the path's points if not specified. + */ + openPopup(latlng?: LatLngExpression): Path; + + /** + * Closes the path's bound popup if it is opened. + */ + closePopup(): Path; + + /** + * Changes the appearance of a Path based on the options in the Path options object. + */ + setStyle(object: PathOptions): Path; + + /** + * Returns the LatLngBounds of the path. + */ + getBounds(): LatLngBounds; + + /** + * Brings the layer to the top of all path layers. + */ + bringToFront(): Path; + + /** + * Brings the layer to the bottom of all path layers. + */ + bringToBack(): Path; + + /** + * Redraws the layer. Sometimes useful after you changed the coordinates that + * the path uses. + */ + redraw(): Path; + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Path; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + fire(type: string, data?: any): Path; + addEventListener(eventMap: any, context?: any): Path; + removeEventListener(eventMap?: any, context?: any): Path; + clearAllEventListeners(): Path; + on(eventMap: any, context?: any): Path; + off(eventMap?: any, context?: any): Path; + } + + export namespace Path { + /** + * True if SVG is used for vector rendering (true for most modern browsers). + */ + export var SVG: boolean; + + /** + * True if VML is used for vector rendering (IE 6-8). + */ + export var VML: boolean; + + /** + * True if Canvas is used for vector rendering (Android 2). You can also force + * this by setting global variable L_PREFER_CANVAS to true before the Leaflet + * include on your page — sometimes it can increase performance dramatically + * when rendering thousands of circle markers, but currently suffers from + * a bug that causes removing such layers to be extremely slow. + */ + export var CANVAS: boolean; + + /** + * How much to extend the clip area around the map view (relative to its size, + * e.g. 0.5 is half the screen in each direction). Smaller values mean that you + * will see clipped ends of paths while you're dragging the map, and bigger values + * decrease drawing performance. + */ + export var CLIP_PADDING: number; + } +} + +declare namespace L { + + export interface PathOptions { + + /** + * Whether to draw stroke along the path. Set it to false to disable borders on + * polygons or circles. + * + * Default value: true. + */ + stroke?: boolean; + + /** + * Stroke color. + * + * Default value: '#03f'. + */ + color?: string; + + /** + * Stroke width in pixels. + * + * Default value: 5. + */ + weight?: number; + + /** + * Stroke opacity. + * + * Default value: 0.5. + */ + opacity?: number; + + /** + * Whether to fill the path with color. Set it to false to disable filling on polygons + * or circles. + */ + fill?: boolean; + + /** + * Fill color. + * + * Default value: same as color. + */ + fillColor?: string; + + /** + * Fill opacity. + * + * Default value: 0.2. + */ + fillOpacity?: number; + + /** + * A string that defines the stroke dash pattern. Doesn't work on canvas-powered + * layers (e.g. Android 2). + */ + dashArray?: string; + + /** + * A string that defines shape to be used at the end of the stroke. + * + * Default: null. + */ + lineCap?: string; + + /** + * A string that defines shape to be used at the corners of the stroke. + * + * Default: null. + */ + lineJoin?: string; + + /** + * If false, the vector will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Sets the pointer-events attribute on the path if SVG backend is used. + */ + pointerEvents?: string; + + /** + * Custom class name set on an element. + * + * Default value: ''. + */ + className?: string; + + /** + * Sets the radius of a circle marker. + */ + radius?: number; + + } +} + +declare namespace L { + + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + function point(x: number, y: number, round?: boolean): Point; + + export interface PointStatic { + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + new(x: number, y: number, round?: boolean): Point; + } + export var Point: PointStatic; + + export interface Point { + /** + * Returns the result of addition of the current and the given points. + */ + add(otherPoint: Point): Point; + + /** + * Returns the result of subtraction of the given point from the current. + */ + subtract(otherPoint: Point): Point; + + /** + * Returns the result of multiplication of the current point by the given number. + */ + multiplyBy(number: number): Point; + + /** + * Returns the result of division of the current point by the given number. If + * optional round is set to true, returns a rounded result. + */ + divideBy(number: number, round?: boolean): Point; + + /** + * Returns the distance between the current and the given points. + */ + distanceTo(otherPoint: Point): number; + + /** + * Returns a copy of the current point. + */ + clone(): Point; + + /** + * Returns a copy of the current point with rounded coordinates. + */ + round(): Point; + + /** + * Returns true if the given point has the same coordinates. + */ + equals(otherPoint: Point): boolean; + + /** + * Returns a string representation of the point for debugging purposes. + */ + toString(): string; + + /** + * The x coordinate. + */ + x: number; + + /** + * The y coordinate. + */ + y: number; + } +} + +declare namespace L { + + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + + + export interface PolygonStatic extends ClassStatic { + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + } + export var Polygon: PolygonStatic; + + export interface Polygon extends Polyline { + } +} + +declare namespace L { + + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + + export interface PolylineStatic extends ClassStatic { + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + } + export var Polyline: PolylineStatic; + + export interface Polyline extends Path { + /** + * Adds a given point to the polyline. + */ + addLatLng(latlng: LatLngExpression): Polyline; + + /** + * Replaces all the points in the polyline with the given array of geographical + * points. + */ + setLatLngs(latlngs: LatLngBoundsExpression): Polyline; + + /** + * Returns an array of the points in the path. + */ + getLatLngs(): LatLng[]; + + /** + * Allows adding, removing or replacing points in the polyline. Syntax is the + * same as in Array#splice. Returns the array of removed points (if any). + */ + spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; + + /** + * Returns the LatLngBounds of the polyline. + */ + getBounds(): LatLngBounds; + + /** + * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + export interface PolylineOptions extends PathOptions { + + /** + * How much to simplify the polyline on each zoom level. More means better performance + * and smoother look, and less means more accurate representation. + * + * Default value: 1.0. + */ + smoothFactor?: number; + + /** + * Disabled polyline clipping. + * + * Default value: false. + */ + noClip?: boolean; + } +} + +declare namespace L { + + namespace PolyUtil { + + /** + * Clips the polygon geometry defined by the given points by rectangular bounds. + * Used by Leaflet to only show polygon points that are on the screen or near, + * increasing performance. Note that polygon points needs different algorithm + * for clipping than polyline, so there's a seperate method for it. + */ + export function clipPolygon(points: Point[], bounds: Bounds): Point[]; + } +} + +declare namespace L { + + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + function popup(options?: PopupOptions, source?: any): Popup; + + export interface PopupStatic extends ClassStatic { + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + new(options?: PopupOptions, source?: any): Popup; + } + export var Popup: PopupStatic; + + export interface Popup extends ILayer { + /** + * Adds the popup to the map. + */ + addTo(map: Map): Popup; + + /** + * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). + */ + openOn(map: Map): Popup; + + /** + * Sets the geographical point where the popup will open. + */ + setLatLng(latlng: LatLngExpression): Popup; + + /** + * Returns the geographical point of popup. + */ + getLatLng(): LatLng; + + /** + * Sets the HTML content of the popup. + */ + setContent(html: string): Popup; + + /** + * Sets the HTML content of the popup. + */ + setContent(el: HTMLElement): Popup; + + /** + * Returns the content of the popup. + */ + getContent(): HTMLElement; + //getContent(): string; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + /** + * Updates the popup content, layout and position. Useful for updating the popup after + * something inside changed, e.g. image loaded. + */ + update(): Popup; + } +} + +declare namespace L { + + export interface PopupOptions { + + /** + * Max width of the popup. + * + * Default value: 300. + */ + maxWidth?: number; + + /** + * Min width of the popup. + * + * Default value: 50. + */ + minWidth?: number; + + /** + * If set, creates a scrollable container of the given height inside a popup + * if its content exceeds it. + */ + maxHeight?: number; + + /** + * Set it to false if you don't want the map to do panning animation to fit the opened + * popup. + * + * Default value: true. + */ + autoPan?: boolean; + + /** + * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. + */ + keepInView?: boolean; + + /** + * Controls the presense of a close button in the popup. + * + * Default value: true. + */ + closeButton?: boolean; + + /** + * The offset of the popup position. Useful to control the anchor of the popup + * when opening it on some overlays. + * + * Default value: new Point(0, 6). + */ + offset?: Point; + + /** + * The margin between the popup and the top left corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingTopLeft?: Point; + + /** + * The margin between the popup and the bottom right corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingBottomRight?: Point; + + /** + * The margin between the popup and the edges of the map view after autopanning + * was performed. + * + * Default value: new Point(5, 5). + */ + autoPanPadding?: Point; + + /** + * Whether to animate the popup on zoom. Disable it if you have problems with + * Flash content inside popups. + * + * Default value: true. + */ + zoomAnimation?: boolean; + + /** + * Set it to false if you want to override the default behavior of the popup + * closing when user clicks the map (set globally by the Map closePopupOnClick + * option). + */ + closeOnClick?: boolean; + + /** + * A custom class name to assign to the popup. + */ + className?: string; + } +} + +declare namespace L { + + export interface PosAnimationStatic extends ClassStatic { + /** + * Creates a PosAnimation object. + */ + new(): PosAnimation; + } + export var PosAnimation: PosAnimationStatic; + + export interface PosAnimation extends IEventPowered { + /** + * Run an animation of a given element to a new position, optionally setting + * duration in seconds (0.25 by default) and easing linearity factor (3rd argument + * of the cubic bezier curve, 0.5 by default) + */ + run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): PosAnimation; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + fire(type: string, data?: any): PosAnimation; + addEventListener(eventMap: any, context?: any): PosAnimation; + removeEventListener(eventMap?: any, context?: any): PosAnimation; + clearAllEventListeners(): PosAnimation; + on(eventMap: any, context?: any): PosAnimation; + off(eventMap?: any, context?: any): PosAnimation; + } +} + +declare namespace L { + + namespace Projection { + + /** + * Spherical Mercator projection — the most common projection for online maps, + * used by almost all free and commercial tile providers. Assumes that Earth + * is a sphere. Used by the EPSG:3857 CRS. + */ + export var SphericalMercator: IProjection; + + /** + * Elliptical Mercator projection — more complex than Spherical Mercator. + * Takes into account that Earth is a geoid, not a perfect sphere. Used by the + * EPSG:3395 CRS. + */ + export var Mercator: IProjection; + + /** + * Equirectangular, or Plate Carree projection — the most simple projection, + * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. + * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple + * CRS. + */ + export var LonLat: IProjection; + } +} + +declare namespace L { + + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; + + export interface RectangleStatic extends ClassStatic { + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + new(bounds: LatLngBounds, options?: PathOptions): Rectangle; + } + export var Rectangle: RectangleStatic; + + export interface Rectangle extends Polygon { + /** + * Redraws the rectangle with the passed bounds. + */ + setBounds(bounds: LatLngBounds): Rectangle; + } +} + + +declare namespace L { + + export interface ScaleOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomleft'. + */ + position?: PositionString; + + /** + * Maximum width of the control in pixels. The width is set dynamically to show + * round values (e.g. 100, 200, 500). + * Default value: 100. + */ + maxWidth?: number; + + /** + * Whether to show the metric scale line (m/km). + * Default value: true. + */ + metric?: boolean; + + /** + * Whether to show the imperial scale line (mi/ft). + * Default value: true. + */ + imperial?: boolean; + + /** + * If true, the control is updated on moveend, otherwise it's always up-to-date + * (updated on move). + * Default value: false. + */ + updateWhenIdle?: boolean; + } +} + +declare namespace L { + + export interface TileLayerStatic extends ClassStatic { + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + new(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + WMS: { + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + new(baseUrl: string, options: WMSOptions): TileLayer.WMS; + }; + + Canvas: { + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + new(options?: TileLayerOptions): TileLayer.Canvas; + }; + } + export var TileLayer: TileLayerStatic; + + export interface TileLayer extends ILayer, IEventPowered { + /** + * Adds the layer to the map. + */ + addTo(map: Map): TileLayer; + + /** + * Brings the tile layer to the top of all tile layers. + */ + bringToFront(): TileLayer; + + /** + * Brings the tile layer to the bottom of all tile layers. + */ + bringToBack(): TileLayer; + + /** + * Changes the opacity of the tile layer. + */ + setOpacity(opacity: number): TileLayer; + + /** + * Sets the zIndex of the tile layer. + */ + setZIndex(zIndex: number): TileLayer; + + /** + * Causes the layer to clear all the tiles and request them again. + */ + redraw(): TileLayer; + + /** + * Updates the layer's URL template and redraws it. + */ + setUrl(urlTemplate: string): TileLayer; + + /** + * Returns the HTML element that contains the tiles for this layer. + */ + getContainer(): HTMLElement; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): TileLayer; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + fire(type: string, data?: any): TileLayer; + addEventListener(eventMap: any, context?: any): TileLayer; + removeEventListener(eventMap?: any, context?: any): TileLayer; + clearAllEventListeners(): TileLayer; + on(eventMap: any, context?: any): TileLayer; + off(eventMap?: any, context?: any): TileLayer; + } + + namespace TileLayer { + export interface WMS extends TileLayer { + /** + * Merges an object with the new parameters and re-requests tiles on the current + * screen (unless noRedraw was set to true). + */ + setParams(params: WMS, noRedraw?: boolean): WMS; + } + + export interface Canvas extends TileLayer { + /** + * You need to define this method after creating the instance to draw tiles; + * canvas is the actual canvas tile on which you can draw, tilePoint represents + * the tile numbers, and zoom is the current zoom. + */ + drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; + + /** + * Calling redraw will cause the drawTile method to be called for all tiles. + * May be used for updating dynamic content drawn on the Canvas + */ + redraw(): Canvas; + } + } + + export interface TileLayerFactory { + + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + (urlTemplate: string, options?: TileLayerOptions): TileLayer; + + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; + + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + canvas(options?: TileLayerOptions): L.TileLayer.Canvas; + } + + export var tileLayer: TileLayerFactory; +} + +declare namespace L { + + export interface TileLayerOptions { + + /** + * Minimum zoom number. + * + * Default value: 0. + */ + minZoom?: number; + + /** + * Maximum zoom number. + * + * Default value: 18. + */ + maxZoom?: number; + + /** + * Maximum zoom number the tiles source has available. If it is specified, + * the tiles on all zoom levels higher than maxNativeZoom will be loaded from + * maxZoom level and auto-scaled. + * + * Default value: null. + */ + maxNativeZoom?: number; + + /** + * Tile size (width and height in pixels, assuming tiles are square). + * + * Default value: 256. + */ + tileSize?: number; + + /** + * Subdomains of the tile service. Can be passed in the form of one string (where + * each letter is a subdomain name) or an array of strings. + * + * Default value: 'abc'. + */ + subdomains?: string|string[]; + + /** + * URL to the tile image to show in place of the tile that failed to load. + * + * Default value: ''. + */ + errorTileUrl?: string; + + /** + * e.g. "© CloudMade" — the string used by the attribution control, describes + * the layer data. + * + * Default value: ''. + */ + attribution?: string; + + /** + * If true, inverses Y axis numbering for tiles (turn this on for TMS services). + * + * Default value: false. + */ + tms?: boolean; + + /** + * If set to true, the tile coordinates won't be wrapped by world width (-180 + * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this + * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor + * or photo maps). + * + * Default value: false. + */ + continuousWorld?: boolean; + + /** + * If set to true, the tiles just won't load outside the world width (-180 to 180 + * longitude) instead of repeating. + * + * Default value: false. + */ + noWrap?: boolean; + + /** + * The zoom number used in tile URLs will be offset with this value. + * + * Default value: 0. + */ + zoomOffset?: number; + + /** + * If set to true, the zoom number used in tile URLs will be reversed (maxZoom + * - zoom instead of zoom) + * + * Default value: false. + */ + zoomReverse?: boolean; + + /** + * The opacity of the tile layer. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * The explicit zIndex of the tile layer. Not set by default. + */ + zIndex?: number; + + /** + * If true, all the tiles that are not visible after panning are removed (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + unloadInvisibleTiles?: boolean; + + /** + * If false, new tiles are loaded during panning, otherwise only after it (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + updateWhenIdle?: boolean; + + /** + * If true and user is on a retina display, it will request four tiles of half the + * specified size and a bigger zoom level in place of one to utilize the high resolution. + * + * Default value: false. + */ + detectRetina?: boolean; + + /** + * If true, all the tiles that are not visible after panning are placed in a reuse + * queue from which they will be fetched when new tiles become visible (as opposed + * to dynamically creating new ones). This will in theory keep memory usage + * low and eliminate the need for reserving new memory whenever a new tile is + * needed. + * + * Default value: false. + */ + reuseTiles?: boolean; + + /** + * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. + */ + bounds?: LatLngBounds; + + /** + * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. + */ + [additionalKeys: string]: any; + } +} + +declare namespace L { + export interface TransformationStatic { + /** + * Creates a transformation object with the given coefficients. + */ + new(a: number, b: number, c: number, d: number): Transformation; + } + export var Transformation: TransformationStatic; + + export interface Transformation { + /** + * Returns a transformed point, optionally multiplied by the given scale. + * Only accepts real L.Point instances, not arrays. + */ + transform(point: Point, scale?: number): Point; + + /** + * Returns the reverse transformation of the given point, optionally divided + * by the given scale. Only accepts real L.Point instances, not arrays. + */ + untransform(point: Point, scale?: number): Point; + } +} + +declare namespace L { + + namespace Util { + + /** + * Merges the properties of the src object (or multiple objects) into dest object + * and returns the latter. Has an L.extend shortcut. + */ + export function extend(dest: any, ...sources: any[]): any; + + /** + * Returns a function which executes function fn with the given scope obj (so + * that this keyword refers to obj inside the function code). Has an L.bind shortcut. + */ + export function bind(fn: T, obj: any): T; + + /** + * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. + */ + export function stamp(obj: any): string; + + /** + * Returns a wrapper around the function fn that makes sure it's called not more + * often than a certain time interval time, but as fast as possible otherwise + * (for example, it is used for checking and requesting new tiles while dragging + * the map), optionally passing the scope (context) in which the function will + * be called. + */ + export function limitExecByInterval(fn: T, time: number, context?: any): T; + + /** + * Returns a function which always returns false. + */ + export function falseFn(): () => boolean; + + /** + * Returns the number num rounded to digits decimals. + */ + export function formatNum(num: number, digits: number): number; + + /** + * Trims and splits the string on whitespace and returns the array of parts. + */ + export function splitWords(str: string): string[]; + + /** + * Merges the given properties to the options of the obj object, returning the + * resulting options. See Class options. Has an L.setOptions shortcut. + */ + export function setOptions(obj: any, options: any): any; + + /** + * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} + * translates to '?a=foo&b=bar'. + */ + export function getParamString(obj: any): string; + + /** + * Simple templating facility, creates a string by applying the values of the + * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form + * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. + */ + export function template(str: string, data: any): string; + + /** + * Returns true if the given object is an array. + */ + export function isArray(obj: any): boolean; + + /** + * Trims the whitespace from both ends of the string and returns the result. + */ + export function trim(str: string): string; + + /** + * Data URI string containing a base64-encoded empty GIF image. Used as a hack + * to free memory from unused images on WebKit-powered mobile devices (by setting + * image src to this string). + */ + export var emptyImageUrl: string; + } +} + + +declare namespace L { + + export interface WMSOptions { + + /** + * (required) Comma-separated list of WMS layers to show. + * + * Default value: ''. + */ + layers?: string; + + /** + * Comma-separated list of WMS styles. + * + * Default value: 'image/jpeg'. + */ + styles?: string; + + /** + * WMS image format (use 'image/png' for layers with transparency). + * + * Default value: false. + */ + format?: string; + + /** + * If true, the WMS service will return images with transparency. + * + * Default value: '1.1.1'. + */ + transparent?: boolean; + + /** + * Version of the WMS service to use. + */ + version?: string; + + } +} + +/** + * Forces Leaflet to use the Canvas back-end (if available) for vector layers + * instead of SVG. This can increase performance considerably in some cases + * (e.g. many thousands of circle markers on the map). + */ +declare var L_PREFER_CANVAS: boolean; + +/** + * Forces Leaflet to not use touch events even if it detects them. + */ +declare var L_NO_TOUCH: boolean; + +/** + * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning + * (which may cause glitches in some rare environments) even if they're supported. + */ +declare var L_DISABLE_3D: boolean; + +declare module "leaflet" { + export = L; +} + +// vim: et ts=4 sw=4 diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index b0568b216a..9b07b8fd03 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -1,427 +1,267 @@ /// -// initialize the map on the "map" div with a given center and zoom - -var div = document.getElementById('map'); - -var map : L.Map = L.map(div, { - center: L.latLng([51.505, -0.09]), - zoom: 13, - minZoom: 3, - maxZoom: 8, - maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), - dragging: true, - touchZoom: true, - scrollWheelZoom: true, - boxZoom: true, - tap: true, - - tapTolerance: 30, - trackResize: true, - worldCopyJump: false, - closePopupOnClick: true, - bounceAtZoomLimits: true, - - keyboard: true, - keyboardPanOffset: 80, - keyboardZoomOffset: 1, - - inertia: true, - inertiaDeceleration: 3000, - inertiaMaxSpeed: 1500, - inertiaThreshold: 32, - - zoomControl: true, - attributionControl: true, - - fadeAnimation: true, - zoomAnimation: true, - zoomAnimationThreshold: 4, - markerZoomAnimation: true - -}); - -map.dragging.enable(); -map.touchZoom.enable(); -map.scrollWheelZoom.enable(); -map.doubleClickZoom.enable(); -map.boxZoom.enable(); -map.tap.enable(); - -map.setView(new L.LatLng(42, 51)); -map.setView(L.latLng(42, 51)); - -map.setView(L.latLng(42, 51), 12); -map.setView(L.latLng(42, 51), 12, { - reset: true, - pan: { - animate: true, - duration: 0.25, - easeLinearity: 0.25, - noMoveStart: false - }, - zoom: { - animate: true - } -}); - -map.setZoom(50); -map.setZoom(50, {}); - -map.zoomIn(); -map.zoomOut(); - -map.zoomIn(2); -map.zoomOut(2); - -map.zoomIn(2, { animate: true }); -map.zoomOut(2, { animate: true }); - -map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); - -map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); -map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { - paddingTopLeft: L.point(20, 20), - paddingBottomRight: L.point(20, 20), - padding: L.point(0, 0), - maxZoom: null -}); - -map.fitWorld(); - -map.fitWorld({ - animate: false -}); - -map.panTo(L.latLng(42, 42)); -map.panTo(L.latLng(42, 42), { - animate: true -}); - -map.invalidateSize(true); -map.invalidateSize({ reset: true }); - -map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); - -map.locate(); -map.locate({ - watch: false, - setView: false, - maxZoom: 18, - timeout: 10000, - maximumAge: 0, - enableHighAccuracy: false -}); - -map.stopLocate(); - -map.remove(); - -var center : L.LatLng = map.getCenter(); -var zoom : number = map.getZoom(); -var minZoom: number = map.getMinZoom(); -var maxZoom: number = map.getMaxZoom(); -var bounds: L.LatLngBounds = map.getBounds(); -var boundsZoom: number = map.getBoundsZoom(bounds, true); -var size: L.Point = map.getSize(); -var pixelBounds: L.Bounds = map.getPixelBounds(); -var pixelOrigin: L.Point = map.getPixelOrigin(); - -var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); - -map.addLayer(layer); -map.addLayer(layer, false); -map.eachLayer(l => {}); - -map.removeLayer(layer); -map.hasLayer(layer); - -map.openPopup("canard", L.latLng(42, 51)); - -var popup = L.popup({ - autoPan: true -}); - -map.openPopup(popup); -map.closePopup(popup); -map.closePopup(); - -map.addControl(L.control.attribution({position: 'bottomright'})); -map.removeControl(L.control.attribution({ position: 'bottomright' })); - -L.control.layers({'Base': layer}).addTo(map); -map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) { - alert(e.name); -}); - -map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); -map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); -map.containerPointToLayerPoint(L.point(0, 0)); -map.layerPointToContainerPoint(L.point(0, 0)); - -map.project(map.unproject(L.point(10, 20))); -map.project(map.unproject(L.point(10, 20), 12), 12); - -var mouseEvent: L.LeafletMouseEvent; -map.mouseEventToContainerPoint(mouseEvent); -map.mouseEventToLayerPoint(mouseEvent); -map.mouseEventToLatLng(mouseEvent); - -map.getContainer().classList.add('roger'); -map.getPanes().mapPane.classList.add('roger'); -map.getPanes().markerPane.classList.add('roger'); -map.getPanes().objectsPane.classList.add('roger'); -map.getPanes().overlayPane.classList.add('roger'); -map.getPanes().popupPane.classList.add('roger'); -map.getPanes().shadowPane.classList.add('roger'); -map.getPanes().tilePane.classList.add('roger'); - -map.whenReady((m: L.Map) => { - m.zoomOut(); -}); - -map.on('click', () => { - map.zoomOut(); -}); - -map.off('dblclick', L.Util.falseFn); - -map.once('contextmenu', (e: L.LeafletMouseEvent) => { - map.openPopup('contextmenu', e.latlng); -}); - -var marker = L.marker(L.latLng(42, 51), { - icon: L.icon({ - iconUrl: 'roger.png', - iconRetinaUrl: 'roger-retina.png', - iconSize: L.point(40, 40), - iconAnchor: L.point(20, 0), - shadowUrl: 'roger-shadow.png', - shadowRetinaUrl: 'roger-shadow-retina.png', - shadowSize: L.point(44, 44), - shadowAnchor: L.point(22, 0), - popupAnchor: L.point(0, 0), - className: 'roger-icon' - }), - clickable: true, - draggable: false, - keyboard: true, - title: 'this is an icon', - alt: '', - zIndexOffset: 0, - opacity: 1.0, - riseOnHover: false, - riseOffset: 250 -}); - -marker.addTo(map); - -marker.on('click', (e: L.LeafletMouseEvent) => { - map.setView(e.latlng); -}); - -marker.once('mouseover', () => { - marker.openPopup(); -}) - -marker.setLatLng(marker.getLatLng()); - -marker.setIcon(L.icon({})); - -marker.setZIndexOffset(30); -marker.setOpacity(0.8); - -marker.bindPopup(popup); -marker.unbindPopup(); -marker.bindPopup('hello', { - closeOnClick: true -}); - -marker.openPopup(); -marker.closePopup(); -marker.togglePopup(); -marker.togglePopup(); -marker.setPopupContent('hello 3') -marker.getPopup().setContent('hello 2'); -marker.update(); - -marker.toGeoJSON(); - -marker.dragging.enable(); - -popup = L.popup({ - maxWidth: 300, - minWidth: 50, - maxHeight: null, - autoPan: true, - keepInView: false, - closeButton: true, - offset: L.point(0, 6), - autoPanPaddingTopLeft: null, - autoPanPaddingBottomRight: L.point(20, 20), - autoPanPadding: L.point(5, 5), - zoomAnimation: true, - closeOnClick: null, - className: 'roger' -}); - -popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); - -popup.update(); - -var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { - minZoom: 0, - maxZoom: 18, - maxNativeZoom: 17, - tileSize: 256, - subdomains: ['a','b','c'], - errorTileUrl: '', - attribution: '', - tms: false, - continuousWorld: false, - noWrap: false, - zoomOffset: 0, - zoomReverse: false, - opacity: 1.0, - zIndex: null, - unloadInvisibleTiles: false, - updateWhenIdle: false, - detectRetina: true, - reuseTiles: true, - bounds: null -}); - -tileLayer.on('loading', L.Util.falseFn) - .off('loading', L.Util.falseFn) - .once('tileload', L.Util.falseFn); - -tileLayer.addTo(map); - -tileLayer.bringToBack() - .bringToFront() - .setOpacity(0.7) - .setZIndex(9) - .redraw() - .setUrl('http://perdu.com') - .getContainer(); - -namespace CustomControl { - export interface Options { - title: string; - position?: string; - } -} -interface CustomControl extends L.Control { - getTitle(): string; - setTitle(title: string): CustomControl; -} -var CustomControl: { new(options: CustomControl.Options): CustomControl }; -CustomControl = L.Control.extend({ - initialize: function(options: CustomControl.Options) { - L.Control.prototype.initialize.call(this, { - position: options.position || 'bottomleft', - }); - this.title = options.title; - }, - getTitle: function() { - return this.title; - }, - setTitle: function(title: string) { - this.title = title; - }, -}); - -// Different latLng and latLngBounds expressions -var latLngLiteral = [10, 20]; -var latLngObjectLiteral = { lat: 10, lng: 10 }; -var boundsLiteral = [[10, 20], [20, 20]]; -var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral]; - -var circle: L.Circle = L.circle(latLngLiteral, 4); -circle = new L.Circle(latLngLiteral, 4); -circle.setLatLng(latLngLiteral); - -circle = L.circle(latLngObjectLiteral, 4); -circle = new L.Circle(latLngObjectLiteral, 4); -circle.setLatLng(latLngObjectLiteral); - -var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral); -circleMarker = new L.CircleMarker(latLngLiteral); -circleMarker.setLatLng(latLngLiteral); - -circleMarker = L.circleMarker(latLngObjectLiteral); -circleMarker = new L.CircleMarker(latLngObjectLiteral); -circleMarker.setLatLng(latLngObjectLiteral); - -var latLng: L.LatLng = L.latLng(latLngLiteral); -latLng = new L.LatLng(latLngLiteral); -latLng.distanceTo(latLngLiteral); -latLng.equals(latLngLiteral); - -latLng = L.latLng(latLngObjectLiteral); -latLng = new L.LatLng(latLngObjectLiteral); -latLng.distanceTo(latLngObjectLiteral); -latLng.equals(latLngObjectLiteral); - -var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral); -bounds = L.latLngBounds(boundLiteralOfLatLngObjects); -bounds = new L.LatLngBounds(boundsLiteral); -bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects); -bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); - -bounds.extend(latLngLiteral); -bounds.extend(latLngObjectLiteral); -bounds.extend(boundsLiteral); -bounds.extend(boundLiteralOfLatLngObjects); - -bounds.contains(latLngLiteral); -bounds.contains(boundLiteralOfLatLngObjects); -bounds.contains(boundsLiteral); - -bounds.intersects(boundsLiteral); -bounds.intersects(boundLiteralOfLatLngObjects); - -bounds.equals(boundsLiteral); -bounds.equals(boundLiteralOfLatLngObjects); - -map.setView(latLngLiteral); -map.setView(latLngObjectLiteral); -map.setZoomAround(latLngLiteral, 15); -map.setZoomAround(latLngObjectLiteral, 15); -map.panTo(latLngLiteral); -map.panTo(latLngObjectLiteral); -map.openPopup('test', latLngLiteral); -map.openPopup('test', latLngObjectLiteral); -map.latLngToLayerPoint(latLngLiteral); -map.latLngToLayerPoint(latLngObjectLiteral); -map.latLngToContainerPoint(latLngLiteral); -map.latLngToContainerPoint(latLngObjectLiteral); -map.project(latLngLiteral); -map.project(latLngObjectLiteral); - -marker.setLatLng(latLngLiteral); -marker.setLatLng(latLngObjectLiteral); - -var polygon: L.Polygon = L.polygon(boundsLiteral); -polygon = L.polygon(boundLiteralOfLatLngObjects); -polygon = new L.Polygon(boundsLiteral); -polygon = new L.Polygon(boundLiteralOfLatLngObjects); - -var polyline: L.Polyline = L.polyline(boundsLiteral); -polyline = L.polyline(boundLiteralOfLatLngObjects); -polyline = new L.Polyline(boundsLiteral); -polyline = new L.Polyline(boundLiteralOfLatLngObjects); -polyline.setLatLngs(boundsLiteral); -polyline.setLatLngs(boundLiteralOfLatLngObjects); -polyline.addLatLng(latLngLiteral); -polyline.addLatLng(latLngObjectLiteral); - -var popup: L.Popup = L.popup(); -popup.setLatLng(latLngLiteral); -popup.setLatLng(latLngObjectLiteral); - -var zoomCtrl = L.control.zoom({ - position: "topleft", - zoomInText: '+', - zoomOutText: '-' -}); +import L = require('leaflet'); + +const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; +const latLngTuple: L.LatLngTuple = [12, 13]; + +let latLng: L.LatLng; +latLng = L.latLng(12, 13); +latLng = L.latLng(12, 13, 0); +latLng = L.latLng(latLngLiteral); +latLng = L.latLng({lat: 12, lng: 13, alt: 0}); +latLng = L.latLng(latLngTuple); +latLng = L.latLng([12, 13, 0]); + +const latLngBoundsLiteral: L.LatLngBoundsLiteral = [[12, 13], latLngTuple]; + +let latLngBounds: L.LatLngBounds; +latLngBounds = L.latLngBounds(latLng, latLng); +latLngBounds = L.latLngBounds(latLngLiteral, latLngLiteral); +latLngBounds = L.latLngBounds(latLngTuple, latLngTuple); + +const pointTuple: L.PointTuple = [0, 0]; + +let point: L.Point; +point = L.point(12, 13); +point = L.point(12, 13, true); +point = L.point(pointTuple); +point = L.point({x: 12, y: 13}); + +const boundsLiteral: L.BoundsLiteral = [[1, 1], pointTuple]; + +let bounds: L.Bounds; +bounds = L.bounds(point, point); +bounds = L.bounds(pointTuple, pointTuple); +bounds = L.bounds([point, point]); +bounds = L.bounds(boundsLiteral); + +let mapOptions: L.MapOptions = {}; +mapOptions = { + preferCanvas: true, + attributionControl: false, + zoomControl: true, + closePopupOnClick: false, + zoomSnap: 1, + zoomDelta: 1, + trackResize: false, + boxZoom: true, + dragging: true, + // CRS + zoom: 12, + minZoom: 10, + maxZoom: 14, + fadeAnimation: true, + markerZoomAnimation: false, + transform3DLimit: 123, + zoomAnimation: false, + zoomAnimationThreshold: 4, + inertia: false, + inertiaDeceleration: 2000, + inertiaMaxSpeed: 1000, + easeLinearity: 0.5, + worldCopyJump: true, + maxBoundsViscosity: 1.0, + keyboard: false, + keyboardPanDelta: 100, + wheelDebounceTime: 30, + wheelPxPerZoomLevel: 25, + tap: false, + tapTolerance: 10, + bounceAtZoomLimits: false +}; + +mapOptions.doubleClickZoom = true; +mapOptions.doubleClickZoom = 'center'; + +mapOptions.center = latLng; +mapOptions.center = latLngLiteral; +mapOptions.center = latLngTuple; + +mapOptions.layers = []; +mapOptions.layers = [L.tileLayer('')]; // add layers of other types + +mapOptions.maxBounds = latLngBounds; +mapOptions.maxBounds = []; +mapOptions.maxBounds = latLngBoundsLiteral; + +// mapOptions.renderer = ? + +mapOptions.scrollWheelZoom = true; +mapOptions.scrollWheelZoom = 'center'; + +mapOptions.touchZoom = false; +mapOptions.touchZoom = 'center'; + +let layer: L.Layer; + +const htmlElement = document.getElementById('foo'); + +let popupOptions: L.PopupOptions = {}; + +let tooltipOptions: L.TooltipOptions = {}; + +let zoomPanOptions: L.ZoomPanOptions = {}; +zoomPanOptions = { + animate: false, + duration: 0.5, + easeLinearity: 0.6, + noMoveStart: true +}; + +let zoomOptions: L.ZoomOptions = {}; + +let panOptions: L.PanOptions = {}; + +let fitBoundsOptions: L.FitBoundsOptions = {}; + +let map = L.map('foo'); +map = L.map('foo', mapOptions); +map = L.map(htmlElement); +map = L.map(htmlElement, mapOptions); + +let doesItHaveLayer: boolean; +doesItHaveLayer = map.hasLayer(L.tileLayer('')); + +// map.getRenderer + +let html: HTMLElement; +html = map.createPane('foo'); +html = map.createPane('foo', htmlElement) +html = map.getPane('foo'); +html = map.getPane(htmlElement); +html = map.getContainer(); + +const panes = map.getPanes(); +html = panes.mapPane; +html = panes.tilePane; +html = panes.overlayPane; +html = panes.shadowPane; +html = panes.markerPane; +html = panes.tooltipPane; +html = panes.popupPane; +html = panes['foo']; + +let coordinates: L.LatLng; +coordinates = map.getCenter(); + +let zoom: number; +zoom = map.getZoom(); +zoom = map.getMinZoom(); +zoom = map.getMaxZoom(); +zoom = map.getBoundsZoom(latLngBounds); +zoom = map.getBoundsZoom(latLngBounds, true); +zoom = map.getBoundsZoom(latLngBoundsLiteral); +zoom = map.getBoundsZoom(latLngBoundsLiteral, true); + +let mapLatLngBounds: L.LatLngBounds; +mapLatLngBounds = map.getBounds(); + +let mapPoint: L.Point; +mapPoint = map.getSize(); +mapPoint = map.getPixelOrigin(); + +let mapPixelBounds: L.Bounds; +mapPixelBounds = map.getPixelBounds(); +mapPixelBounds = map.getPixelWorldBounds(); +mapPixelBounds = map.getPixelWorldBounds(12); + +map = map + // addControl + // removeControl + .addLayer(L.tileLayer('')) + .removeLayer(L.tileLayer('')) // use a different type of layer + .eachLayer((currentLayer) => { + layer = currentLayer; + }) + .eachLayer((currentLayer) => { + layer = currentLayer; + }, {}) + .openPopup(L.popup()) + .openPopup('Hello World', latLng) + .openPopup('Hello World', latLng, popupOptions) + .openPopup('Hello World', latLngLiteral) + .openPopup('Hello World', latLngLiteral, popupOptions) + .openPopup('Hello World', latLngTuple) + .openPopup('Hello World', latLngTuple, popupOptions) + .openPopup(htmlElement, latLng) + .openPopup(htmlElement, latLng, popupOptions) + .openPopup(htmlElement, latLngLiteral) + .openPopup(htmlElement, latLngLiteral, popupOptions) + .openPopup(htmlElement, latLngTuple) + .openPopup(htmlElement, latLngTuple, popupOptions) + .closePopup() + .closePopup(L.popup()) + .openTooltip(L.tooltip()) + .openTooltip('Hello Word', latLng) + .openTooltip('Hello World', latLng, tooltipOptions) + .openTooltip('Hello World', latLngLiteral) + .openTooltip('Hello World', latLngLiteral, tooltipOptions) + .openTooltip('Hello World', latLngTuple) + .openTooltip('Hello World', latLngTuple, tooltipOptions) + .openTooltip(htmlElement, latLng) + .openTooltip(htmlElement, latLng, tooltipOptions) + .openTooltip(htmlElement, latLngLiteral) + .openTooltip(htmlElement, latLngLiteral, tooltipOptions) + .openTooltip(htmlElement, latLngTuple) + .openTooltip(htmlElement, latLngTuple, tooltipOptions) + .closeTooltip() + .closeTooltip(L.tooltip()) + .setView(latLng, 12) + .setView(latLng, 12, zoomPanOptions) + .setView(latLngLiteral, 12) + .setView(latLngLiteral, 12, zoomPanOptions) + .setView(latLngTuple, 12) + .setView(latLngTuple, 12, zoomPanOptions) + .setZoom(12, zoomPanOptions) // investigate if zoomPanOptions are really required + .zoomIn() + .zoomIn(1) + .zoomIn(1, zoomOptions) + .zoomOut() + .zoomOut(1) + .zoomOut(1, zoomOptions) + .setZoomAround(latLng, 12, zoomOptions) // investigate if zoom options are really required + .setZoomAround(latLngLiteral, 12, zoomOptions) + .setZoomAround(latLngTuple, 12, zoomOptions) + .setZoomAround(point, 12, zoomOptions) + .setZoomAround(pointTuple, 11, zoomOptions) + .fitBounds(latLngBounds, fitBoundsOptions) // investigate if fit bounds options are really required + .fitBounds(latLngBoundsLiteral, fitBoundsOptions) + .fitWorld() + .fitWorld(fitBoundsOptions) + .panTo(latLng) + .panTo(latLng, panOptions) + .panTo(latLngLiteral) + .panTo(latLngLiteral, panOptions) + .panTo(latLngTuple) + .panTo(latLngTuple, panOptions) + .panBy(point) + .panBy(pointTuple) + .setMaxBounds(bounds) // investigate if this really receives Bounds instead of LatLngBounds + .setMaxBounds(boundsLiteral) + .setMinZoom(5) + .setMaxZoom(10) + .panInsideBounds(latLngBounds) + .panInsideBounds(latLngBounds, panOptions) + .panInsideBounds(latLngBoundsLiteral) + .panInsideBounds(latLngBoundsLiteral, panOptions) + .invalidateSize(zoomPanOptions) + .invalidateSize(false) + .stop() + .flyTo(latLng) + .flyTo(latLng, 12) + .flyTo(latLng, 12, zoomOptions) + .flyTo(latLngLiteral) + .flyTo(latLngLiteral, 12) + .flyTo(latLngLiteral, 12, zoomPanOptions) + .flyTo(latLngTuple) + .flyTo(latLngTuple, 12) + .flyTo(latLngTuple, 12, zoomPanOptions) + .flyToBounds(latLngBounds) + .flyToBounds(latLngBounds, fitBoundsOptions) + .flyToBounds(latLngBoundsLiteral) + .flyToBounds(latLngBoundsLiteral, fitBoundsOptions) + // addHandler + .remove() + .whenReady(() => {}) + .whenReady(() => {}, {}); diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 3bf19a1771..87f33576e6 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,4382 +1,927 @@ -// Type definitions for Leaflet.js 1.0.0 +// Type definitions for Leaflet.js 1.0.0-rc3 // Project: https://github.com/Leaflet/Leaflet -// Definitions by: Vladimir Zotov +// Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace L { - type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) - type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; - type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; -} - -declare namespace L { - - export interface AttributionOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomright'. - */ - position?: PositionString; - - /** - * The HTML text shown before the attributions. Pass false to disable. - * Default value: 'Powered by Leaflet'. - */ - prefix?: string; - - } -} - -declare namespace L { - - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - export function bounds(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - export function bounds(points: Point[]): Bounds; - - - export interface BoundsStatic { - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - new(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - new(points: Point[]): Bounds; - } - export var Bounds: BoundsStatic; - - export interface Bounds { - /** - * Extends the bounds to contain the given point. - */ - extend(point: Point): void; - - /** - * Returns the center point of the bounds. - */ - getCenter(): Point; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: Bounds): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(point: Point): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: Bounds): boolean; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; - - /** - * Returns the size of the given bounds. - */ - getSize(): Point; - - /** - * The top left corner of the rectangle. - */ - min: Point; - - /** - * The bottom right corner of the rectangle. - */ - max: Point; - } -} - -declare namespace L { - - namespace Browser { - - /** - * true for all Internet Explorer versions. - */ - export var ie: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie6: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie7: boolean; - - /** - * true for webkit-based browsers like Chrome and Safari (including mobile - * versions). - */ - export var webkit: boolean; - - /** - * true for webkit-based browsers that support CSS 3D transformations. - */ - export var webkit3d: boolean; - - /** - * true for Android mobile browser. - */ - export var android: boolean; - - /** - * true for old Android stock browsers (2 and 3). - */ - export var android23: boolean; - - /** - * true for modern mobile browsers (including iOS Safari and different Android - * browsers). - */ - export var mobile: boolean; - - /** - * true for mobile webkit-based browsers. - */ - export var mobileWebkit: boolean; - - /** - * true for mobile Opera. - */ - export var mobileOpera: boolean; - - /** - * true for all browsers on touch devices. - */ - export var touch: boolean; - - /** - * true for browsers with Microsoft touch model (e.g. IE10). - */ - export var msTouch: boolean; - - /** - * true for devices with Retina screens. - */ - export var retina: boolean; - - } -} - - -declare namespace L { - - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - - export interface CircleStatic extends ClassStatic { - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - } - export var Circle: CircleStatic; - - export interface Circle extends Path { - /** - * Returns the current geographical position of the circle. - */ - getLatLng(): LatLng; - - /** - * Returns the current radius of a circle. Units are in meters. - */ - getRadius(): number; - - /** - * Sets the position of a circle to a new location. - */ - setLatLng(latlng: LatLngExpression): Circle; - - /** - * Sets the radius of a circle. Units are in meters. - */ - setRadius(radius: number): Circle; - - /** - * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). - */ - toGeoJSON(): GeoJSON.Feature; - - } -} - -declare namespace L { - - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - - - export interface CircleMarkerStatic extends ClassStatic { - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - } - export var CircleMarker: CircleMarkerStatic; - - export interface CircleMarker extends Circle { - /** - * Sets the position of a circle marker to a new location. - */ - setLatLng(latlng: LatLngExpression): CircleMarker; - - /** - * Sets the radius of a circle marker. Units are in pixels. - */ - setRadius(radius: number): CircleMarker; - } -} - -declare namespace L { - export interface ClassExtendOptions { - /** - * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. - */ - initialize?: Function; - - /** - * options is a special property that unlike other objects that you pass - * to extend will be merged with the parent one instead of overriding it - * completely, which makes managing configuration of objects and default - * values convenient. - */ - options?: any; - - /** - * includes is a special class property that merges all specified objects - * into the class (such objects are called mixins). A good example of this - * is L.Mixin.Events that event-related methods like on, off and fire - * to the class. - */ - includes?: any; - - /** - * statics is just a convenience property that injects specified object - * properties as the static properties of the class, useful for defining - * constants. - */ - static?: any; - - [prop: string]: any; - } - - export interface ClassStatic { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - extend(options: ClassExtendOptions): any; - extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; - - /** - * You can also use the following shortcut when you just need to make - * one additional method call. - */ - addInitHook(methodName: string, ...args: any[]): void; - } - - - /** - * L.Class powers the OOP facilities of Leaflet and is used to create - * almost all of the Leaflet classes documented. - */ - namespace Class { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - function extend(options: ClassExtendOptions): any; - } - -} - -declare namespace L { - export interface ControlStatic extends ClassStatic { - /** - * Creates a control with the given options. - */ - new(options?: ControlOptions): Control; - - Zoom: Control.ZoomStatic; - Attribution: Control.AttributionStatic; - Layers: Control.LayersStatic; - Scale: Control.ScaleStatic; - } - export var Control: ControlStatic; - - export interface Control extends IControl { - /** - * Sets the position of the control. See control positions. - */ - setPosition(position: PositionString): Control; - - /** - * Returns the current position of the control. - */ - getPosition(): PositionString; - - /** - * Adds the control to the map. - */ - addTo(map: Map): Control; - - /** - * Removes the control from the map. - */ - removeFrom(map: Map): Control; - - /** - * Returns the HTML container of the control. - */ - getContainer(): HTMLElement; - - // IControl members - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } - - namespace Control { - export interface ZoomStatic extends ClassStatic { - /** - * Creates a zoom control. - */ - new (options?: ZoomOptions): Zoom; - } - - export interface Zoom extends L.Control { - } - - export interface ZoomOptions { - /** - * The position of the control (one of the map corners). - * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. - * - * Default value: 'topright'. - */ - position?: PositionString; - - /** - * The text set on the zoom in button. - * - * Default value: '+' - */ - zoomInText?: string; - - /** - * The text set on the zoom out button. - * - * Default value: '-' - */ - zoomOutText?: string; - - /** - * The title set on the zoom in button. - * - * Default value: 'Zoom in' - */ - zoomInTitle?: string; - - /** - * The title set on the zoom out button. - * - * Default value: 'Zoom out' - */ - zoomOutTitle?: string; - } - - export interface AttributionStatic extends ClassStatic { - /** - * Creates an attribution control. - */ - new(options?: AttributionOptions): Attribution; - } - - export interface Attribution extends L.Control { - /** - * Sets the text before the attributions. - */ - setPrefix(prefix: string): Attribution; - - /** - * Adds an attribution text (e.g. 'Vector data © CloudMade'). - */ - addAttribution(text: string): Attribution; - - /** - * Removes an attribution text. - */ - removeAttribution(text: string): Attribution; - - } - - export interface LayersStatic extends ClassStatic { - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; - } - - export interface Layers extends L.Control, IEventPowered { - /** - * Adds a base layer (radio button entry) with the given name to the control. - */ - addBaseLayer(layer: ILayer, name: string): Layers; - - /** - * Adds an overlay (checkbox entry) with the given name to the control. - */ - addOverlay(layer: ILayer, name: string): Layers; - - /** - * Remove the given layer from the control. - */ - removeLayer(layer: ILayer): Layers; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Layers; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - fire(type: string, data?: any): Layers; - addEventListener(eventMap: any, context?: any): Layers; - removeEventListener(eventMap?: any, context?: any): Layers; - clearAllEventListeners(): Layers; - on(eventMap: any, context?: any): Layers; - off(eventMap?: any, context?: any): Layers; - } - - export interface ScaleStatic extends ClassStatic { - /** - * Creates an scale control with the given options. - */ - new(options?: ScaleOptions): Scale; - } - - export interface Scale extends L.Control { - } - } - - export interface control { - /** - * Creates a control with the given options. - */ - (options?: ControlOptions): Control; - } - - export namespace control { - - /** - * Creates a zoom control. - */ - export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; - - /** - * Creates an attribution control. - */ - export function attribution(options?: AttributionOptions): L.Control.Attribution; - - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; - - /** - * Creates an scale control with the given options. - */ - export function scale(options?: ScaleOptions): L.Control.Scale; - } -} - -declare namespace L { - - export interface ControlOptions { - - /** - * The initial position of the control (one of the map corners). See control - * positions. - * Default value: 'topright'. - */ - position?: PositionString; - - } -} - -declare namespace L { - - namespace CRS { - - /** - * The most common CRS for online maps, used by almost all free and commercial - * tile providers. Uses Spherical Mercator projection. Set in by default in - * Map's crs option. - */ - export var EPSG3857: ICRS; - - /** - * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. - */ - export var EPSG4326: ICRS; - - /** - * Rarely used by some commercial tile providers. Uses Elliptical Mercator - * projection. - */ - export var EPSG3395: ICRS; - - /** - * A simple CRS that maps longitude and latitude into x and y directly. May be - * used for maps of flat surfaces (e.g. game maps). Note that the y axis should - * still be inverted (going from bottom to top). - */ - export var Simple: ICRS; - - } -} - -declare namespace L { - - /** - * Creates a div icon instance with the given options. - */ - function divIcon(options: DivIconOptions): DivIcon; - - export interface DivIconStatic extends ClassStatic { - /** - * Creates a div icon instance with the given options. - */ - new(options: DivIconOptions): DivIcon; - } - export var DivIcon: DivIconStatic; - - export interface DivIcon extends Icon { - } -} - -declare namespace L { - - export interface DivIconOptions { - - /** - * Size of the icon in pixels. Can be also set through CSS. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to the icon. - * - * Default value: 'leaflet-div-icon'. - */ - className?: string; - - /** - * A custom HTML code to put inside the div element. - * - * Default value: ''. - */ - html?: string; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - } -} - -declare namespace L { - - export interface DomEvent { - - /** - * Adds a listener fn to the element's DOM event of the specified type. this keyword - * inside the listener will point to context, or to the element if not specified. - */ - addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Removes an event listener from the element. - */ - removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Stop the given event from propagation to parent elements. Used inside the - * listener functions: - * L.DomEvent.addListener(div, 'click', function - * (e) { - * L.DomEvent.stopPropagation(e); - * }); - */ - stopPropagation(e: Event): DomEvent; - - /** - * Prevents the default action of the event from happening (such as following - * a link in the href of the a element, or doing a POST request with page reload - * when form is submitted). Use it inside listener functions. - */ - preventDefault(e: Event): DomEvent; - - /** - * Does stopPropagation and preventDefault at the same time. - */ - stop(e: Event): DomEvent; - - /** - * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' - * and 'touchstart' events. - */ - disableClickPropagation(el: HTMLElement): DomEvent; - - /** - * Gets normalized mouse position from a DOM event relative to the container - * or to the whole page if not specified. - */ - getMousePosition(e: Event, container?: HTMLElement): Point; - - /** - * Gets normalized wheel delta from a mousewheel DOM event. - */ - getWheelDelta(e: Event): number; - - } - - export var DomEvent: DomEvent; -} - -declare namespace L { - - namespace DomUtil { - - /** - * Returns an element with the given id if a string was passed, or just returns - * the element if it was passed directly. - */ - export function get(id: string): HTMLElement; - - /** - * Returns the value for a certain style attribute on an element, including - * computed values or values set through CSS. - */ - export function getStyle(el: HTMLElement, style: string): string; - - /** - * Returns the offset to the viewport for the requested element. - */ - export function getViewportOffset(el: HTMLElement): Point; - - /** - * Creates an element with tagName, sets the className, and optionally appends - * it to container element. - */ - export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; - - /** - * Makes sure text cannot be selected, for example during dragging. - */ - export function disableTextSelection(): void; - - /** - * Makes text selection possible again. - */ - export function enableTextSelection(): void; - - /** - * Returns true if the element class attribute contains name. - */ - export function hasClass(el: HTMLElement, name: string): boolean; - - /** - * Adds name to the element's class attribute. - */ - export function addClass(el: HTMLElement, name: string): void; - - /** - * Removes name from the element's class attribute. - */ - export function removeClass(el: HTMLElement, name: string): void; - - /** - * Set the opacity of an element (including old IE support). Value must be from - * 0 to 1. - */ - export function setOpacity(el: HTMLElement, value: number): void; - - /** - * Goes through the array of style names and returns the first name that is a valid - * style name for an element. If no such name is found, it returns false. Useful - * for vendor-prefixed styles like transform. - */ - export function testProp(props: string[]): any; - - /** - * Returns a CSS transform string to move an element by the offset provided in - * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms - * and 2D on other browsers. - */ - export function getTranslateString(point: Point): string; - - /** - * Returns a CSS transform string to scale an element (with the given scale origin). - */ - export function getScaleString(scale: number, origin: Point): string; - - /** - * Sets the position of an element to coordinates specified by point, using - * CSS translate or top/left positioning depending on the browser (used by - * Leaflet internally to position its layers). Forces top/left positioning - * if disable3D is true. - */ - export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; - - /** - * Returns the coordinates of an element previously positioned with setPosition. - */ - export function getPosition(el: HTMLElement): Point; - - /** - * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). - */ - export var TRANSITION: string; - - /** - * Vendor-prefixed transform style name. - */ - export var TRANSFORM: string; - - } -} - -declare namespace L { - export interface DraggableStatic extends ClassStatic { - /** - * Creates a Draggable object for moving the given element when you start dragging - * the dragHandle element (equals the element itself by default). - */ - new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; - } - export var Draggable: DraggableStatic; - - - export interface Draggable extends IEventPowered { - /** - * Enables the dragging ability. - */ - enable(): void; - - /** - * Disables the dragging ability. - */ - disable(): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Draggable; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - fire(type: string, data?: any): Draggable; - addEventListener(eventMap: any, context?: any): Draggable; - removeEventListener(eventMap?: any, context?: any): Draggable; - clearAllEventListeners(): Draggable; - on(eventMap: any, context?: any): Draggable; - off(eventMap?: any, context?: any): Draggable; - } -} - - - -declare namespace L { - - /** - * Create a layer group, optionally given an initial set of layers. - */ - function featureGroup(layers?: T[]): FeatureGroup; - - - export interface FeatureGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): FeatureGroup; - } - export var FeatureGroup: FeatureGroupStatic; - - export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { - /** - * Binds a popup with a particular HTML content to a click on any layer from the - * group that has a bindPopup method. - */ - bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; - - /** - * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates - * of its children). - */ - getBounds(): LatLngBounds; - - /** - * Sets the given path options to each layer of the group that has a setStyle method. - */ - setStyle(style: PathOptions): FeatureGroup; - - /** - * Brings the layer group to the top of all other layers. - */ - bringToFront(): FeatureGroup; - - /** - * Brings the layer group to the bottom of all other layers. - */ - bringToBack(): FeatureGroup; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): FeatureGroup; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - fire(type: string, data?: any): FeatureGroup; - addEventListener(eventMap: any, context?: any): FeatureGroup; - removeEventListener(eventMap?: any, context?: any): FeatureGroup; - clearAllEventListeners(): FeatureGroup; - on(eventMap: any, context?: any): FeatureGroup; - off(eventMap?: any, context?: any): FeatureGroup; - } -} - -declare namespace L { - - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - export interface GeoJSONStatic extends ClassStatic { - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - new(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - /** - * Creates a layer from a given GeoJSON feature. - */ - geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; - - /** - * Creates a LatLng object from an array of 2 numbers (latitude, longitude) - * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted - * as (longitude, latitude). - */ - coordsToLatLng(coords: number[], reverse?: boolean): LatLng; - - /** - * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates - * array. levelsDeep specifies the nesting level (0 is for an array of points, - * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to - * true, the numbers will be interpreted as (longitude, latitude). - */ - coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; - } - export var GeoJSON: GeoJSONStatic; - - export interface GeoJSON extends FeatureGroup { - /** - * Adds a GeoJSON object to the layer. - */ - addData(data: any): boolean; - - /** - * Changes styles of GeoJSON vector layers with the given style function. - */ - setStyle(style: (featureData: any) => any): GeoJSON; - - /** - * Changes styles of GeoJSON vector layers with the given style options. - */ - setStyle(style: PathOptions): GeoJSON; - - /** - * Resets the the given vector layer's style to the original GeoJSON style, - * useful for resetting style after hover events. - */ - resetStyle(layer: Path): GeoJSON; - } -} - -declare namespace L { - export interface GeoJSONOptions { - /** - * Function that will be used for creating layers for GeoJSON points (if not - * specified, simple markers will be created). - */ - pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; - - /** - * Function that will be used to get style options for vector layers created - * for GeoJSON features. - */ - style?: (featureData: any) => any; - - /** - * Function that will be called on each created feature layer. Useful for attaching - * events and popups to features. - */ - onEachFeature?: (featureData: any, layer: ILayer) => void; - - /** - * Function that will be used to decide whether to show a feature or not. - */ - filter?: (featureData: any, layer: ILayer) => boolean; - - /** - * Function that will be used for converting GeoJSON coordinates to LatLng points - * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] - * values in degrees). - */ - coordsToLatLng?: (coords: any[]) => LatLng[]; - } -} - - - - -declare namespace L { - - /** - * Creates an icon instance with the given options. - */ - function icon(options: IconOptions): Icon; - - export interface IconStatic extends ClassStatic { - /** - * Creates an icon instance with the given options. - */ - new(options: IconOptions): Icon; - - Default: { - /** - * Creates a default icon instance with the given options. - */ - new(options?: IconOptions): Icon.Default; - - imagePath: string; - }; - } - export var Icon: IconStatic; - - export interface Icon { - } - - namespace Icon { - /** - * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses - * for markers by default. - */ - export interface Default extends Icon { - } - } -} - -declare namespace L { - - export interface IconOptions { - - /** - * (required) The URL to the icon image (absolute or relative to your script - * path). - */ - iconUrl?: string; - - /** - * The URL to a retina sized version of the icon image (absolute or relative to - * your script path). Used for Retina screen devices. - */ - iconRetinaUrl?: string; - - /** - * Size of the icon image in pixels. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * The URL to the icon shadow image. If not specified, no shadow image will be - * created. - */ - shadowUrl?: string; - - /** - * The URL to the retina sized version of the icon shadow image. If not specified, - * no shadow image will be created. Used for Retina screen devices. - */ - shadowRetinaUrl?: string; - - /** - * Size of the shadow image in pixels. - */ - shadowSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the shadow (relative to its top left corner) - * (the same as iconAnchor if not specified). - */ - shadowAnchor?: Point|[number, number]; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to both icon and shadow images. Empty by default. - */ - className?: string; - } -} - -declare namespace L { - - export interface IControl { - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ICRS { - - /** - * Projection that this CRS uses. - */ - projection: IProjection; - - /** - * Transformation that this CRS uses to turn projected coordinates into screen - * coordinates for a particular tile service. - */ - transformation: Transformation; - - /** - * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). - */ - code: string; - - /** - * Projects geographical coordinates on a given zoom into pixel coordinates. - */ + export interface CRS { latLngToPoint(latlng: LatLng, zoom: number): Point; - - /** - * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom - * into geographical coordinates. - */ - pointToLatLng(point: Point, zoom: number): LatLng; - - /** - * Projects geographical coordinates into coordinates in units accepted - * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). - */ + latLngToPoint(latlng: LatLngLiteral, zoom: number): Point; + latLngToPoint(latlng: LatLngTuple, zoom: number): Point; + pointToLatLng(point: Point): LatLng; + pointToLatLng(point: PointTuple): LatLng; project(latlng: LatLng): Point; - - /** - * Returns the scale used when transforming projected coordinates into pixel - * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for - * Mercator-based CRS. - */ - scale(zoom: number): number; - - /** - * Returns the size of the world in pixels for a particular zoom. - */ - getSize(zoom: number): Point; - - } -} - -declare namespace L { - - export interface IEventPowered { - - /** - * Adds a listener function (fn) to a particular event type of the object. You - * can optionally specify the context of the listener (object the this keyword - * will point to). You can also pass several space-separated types (e.g. 'click - * dblclick'). - */ - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * The same as above except the listener will only get fired once and then removed. - */ - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - /** - * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} - */ - addEventListener(eventMap: any, context?: any): T; - - /** - * Removes a previously added listener function. If no function is specified, - * it will remove all the listeners of that particular event from the object. - */ - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Removes a set of type/listener pairs. - */ - removeEventListener(eventMap?: any, context?: any): T; - - /** - * Returns true if a particular event type has some listeners attached to it. - */ - hasEventListeners(type: string): boolean; - - /** - * Fires an event of the specified type. You can optionally provide an data object - * — the first argument of the listener function will contain its properties. - */ - fireEvent(type: string, data?: any): T; - - /** - * Removes all listeners to all events on the object. - */ - clearAllEventListeners(): T; - - /** - * Alias to addEventListener. - */ - on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to addEventListener. - */ - on(eventMap: any, context?: any): T; - - /** - * Alias to addOneTimeEventListener. - */ - once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(eventMap?: any, context?: any): T; - - /** - * Alias to fireEvent. - */ - fire(type: string, data?: any): T; - } -} - -declare namespace L { - - export interface IHandler { - - /** - * Enables the handler. - */ - enable(): void; - - /** - * Disables the handler. - */ - disable(): void; - - /** - * Returns true if the handler is enabled. - */ - enabled(): boolean; - } - - export interface Handler { - initialize(map: Map): void; - } -} - -declare namespace L { - - export interface ILayer { - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - namespace Mixin { - export interface LeafletMixinEvents extends IEventPowered { - } - - export var Events: LeafletMixinEvents; - } -} - -declare namespace L { - - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - - export interface ImageOverlayStatic extends ClassStatic { - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - } - export var ImageOverlay: ImageOverlayStatic; - - export interface ImageOverlay extends ILayer { - /** - * Adds the overlay to the map. - */ - addTo(map: Map): ImageOverlay; - - /** - * Sets the opacity of the overlay. - */ - setOpacity(opacity: number): ImageOverlay; - - /** - * Changes the URL of the image. - */ - setUrl(imageUrl: string): ImageOverlay; - - /** - * Brings the layer to the top of all overlays. - */ - bringToFront(): ImageOverlay; - - /** - * Brings the layer to the bottom of all overlays. - */ - bringToBack(): ImageOverlay; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ImageOverlayOptions { - - /** - * The opacity of the image overlay. - */ - opacity?: number; - } -} - -declare namespace L { - - export interface IProjection { - - /** - * Projects geographical coordinates into a 2D point. - */ - project(latlng: LatLng): Point; - - /** - * The inverse of project. Projects a 2D point into geographical location. - */ + project(latlng: LatLngLiteral): Point; + project(latlng: LatLngTuple): Point; unproject(point: Point): LatLng; + unproject(point: PointTuple): LatLng; + scale(zoom: number): number; + zoom(scale: number): number; + getProjectedBounds(zoom: number): Bounds; + distance(latlng1: LatLng, latlng2: LatLng): number; + distance(latlng1: LatLngLiteral, latlng2: LatLngLiteral): number; + distance(latlng1: LatLngTuple, latlng2: LatLngTuple): number; + wrapLatLng(latlng: LatLng): LatLng; + wrapLatLng(latlng: LatLngLiteral): LatLng; + wrapLatLng(latlng: LatLngTuple): LatLng; + + code: string; + wrapLng: [number, number]; + wrapLat: [number, number]; + infinite: boolean; } -} -declare namespace L { - - /** - * A constant that represents the Leaflet version in use. - */ - export var version: string; - - /** - * This method restores the L global variale to the original value it had - * before Leaflet inclusion, and returns the real Leaflet namespace. - */ - export function noConflict(): typeof L; -} - -declare namespace L { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(coords: LatLngExpression): LatLng; - - export interface LatLngStatic { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(coords: LatLngExpression): LatLng; - - /** - * A multiplier for converting degrees into radians. - * - * Value: Math.PI / 180. - */ - DEG_TO_RAD: number; - - /** - * A multiplier for converting radians into degrees. - * - * Value: 180 / Math.PI. - */ - RAD_TO_DEG: number; - - /** - * Max margin of error for the equality check. - * - * Value: 1.0E-9. - */ - MAX_MARGIN: number; + export namespace CRS { + export const EPSG3395: CRS; + export const EPSG3857: CRS; + export const EPSG4326: CRS; + export const Earth: CRS; + export const Simple: CRS; + } + + export interface Projection { + project(latlng: LatLng): Point; + project(latlng: LatLngLiteral): Point; + project(latlng: LatLngTuple): Point; + unproject(point: Point): LatLng; + unproject(point: PointTuple): LatLng; + + bounds: LatLngBounds; + } + + export namespace Projection { + export const LonLat: Projection; + export const Mercator: Projection; + export const SphericalMercator: Projection; } - export var LatLng: LatLngStatic; export interface LatLng { - /** - * Returns the distance (in meters) to the given LatLng calculated using the - * Haversine formula. See description on wikipedia - */ - distanceTo(otherLatlng: LatLngExpression): number; - - /** - * Returns true if the given LatLng point is at the same position (within a small - * margin of error). - */ - equals(otherLatlng: LatLngExpression): boolean; - - /** - * Returns a string representation of the point (for debugging purposes). - */ + equals(otherLatLng: LatLng, maxMargin?: number): boolean; + equals(otherLatLng: LatLngLiteral, maxMargin?: number): boolean; + equals(otherLatLng: LatLngTuple, maxMargin?: number): boolean; toString(): string; + distanceTo(otherLatLng: LatLng): number; + distanceTo(otherLatLng: LatLngLiteral): number; + distanceTo(otherLatLng: LatLngTuple): number; + wrap(): LatLng; + toBounds(sizeInMeters: number): LatLngBounds; - /** - * Returns a new LatLng object with the longitude wrapped around left and right - * boundaries (-180 to 180 by default). - */ - wrap(left?: number, right?: number): LatLng; - - /** - * Latitude in degrees. - */ lat: number; + lng: number; + alt: number; + } - /** - * Longitude in degrees. - */ + export interface LatLngLiteral { + lat: number; lng: number; } -} -declare namespace L { + export type LatLngTuple = [number, number]; - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + type LatLngExpression = LatLng | LatLngLiteral | LatLngTuple; - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + export function latLng(latitude: number, longitude: number, altitude?: number): LatLng; - export interface LatLngBoundsStatic { - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + export function latLng(coords: LatLngTuple): LatLng; - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - new(latlngs: LatLngBoundsExpression): LatLngBounds; - } - export var LatLngBounds: LatLngBoundsStatic; + export function latLng(coords: [number, number, number]): LatLng; + + export function latLng(coords: LatLngLiteral): LatLng; + + export function latLng(coords: {lat: number, lng: number, alt: number}): LatLng; export interface LatLngBounds { - /** - * Extends the bounds to contain the given point. - */ - extend(latlng: LatLngExpression): LatLngBounds; - - /** - * Extends the bounds to contain the given bounds. - */ - extend(latlng: LatLngBoundsExpression): LatLngBounds; - - /** - * Returns the south-west point of the bounds. - */ + extend(latlng: LatLng): this; + extend(latlng: LatLngLiteral): this; + extend(latlng: LatLngTuple): this; + extend(otherBounds: LatLngBounds): this; + extend(otherBounds: LatLngBoundsLiteral): this; + pad(bufferRatio: number): LatLngBounds; // does this modify the current instance or does it return a new one? + getCenter(): LatLng; getSouthWest(): LatLng; - - /** - * Returns the north-east point of the bounds. - */ getNorthEast(): LatLng; - - /** - * Returns the north-west point of the bounds. - */ getNorthWest(): LatLng; - - /** - * Returns the south-east point of the bounds. - */ getSouthEast(): LatLng; - - /** - * Returns the west longitude in degrees of the bounds. - */ - getWest(): number; - - /** - * Returns the east longitude in degrees of the bounds. - */ - getEast(): number; - - /** - * Returns the north latitude in degrees of the bounds. - */ - getNorth(): number; - - /** - * Returns the south latitude in degrees of the bounds. - */ - getSouth(): number; - - /** - * Returns the center point of the bounds. - */ - getCenter(): LatLng; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(latlng: LatLngExpression): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle is equivalent (within a small margin of error) - * to the given bounds. - */ - equals(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' - * format. Useful for sending requests to web services that return geo data. - */ + getWest(): number; + getSouth(): number; + getEast(): number; + getNorth(): number; + contains(otherBounds: LatLngBounds): boolean; + contains(otherBounds: LatLngBoundsLiteral): boolean; + contains(latlng: LatLng): boolean; + contains(latlng: LatLngLiteral): boolean; + contains(latlng: LatLngTuple): boolean; + intersects(otherBounds: LatLngBounds): boolean; + intersects(otherBounds: LatLngLiteral): boolean; + overlaps(otherBounds: Bounds): boolean; // investigate if this is really bounds and not latlngbounds + overlaps(otherBounds: BoundsLiteral): boolean; toBBoxString(): string; - - /** - * Returns bigger bounds created by extending the current bounds by a given - * percentage in each direction. - */ - pad(bufferRatio: number): LatLngBounds; - - /** - * Returns true if the bounds are properly initialized. - */ + equals(otherBounds: LatLngBounds): boolean; + equals(otherBounds: LatLngBoundsLiteral): boolean; isValid(): boolean; - } -} -declare namespace L { + export type LatLngBoundsLiteral = Array; - /** - * Create a layer group, optionally given an initial set of layers. - */ - function layerGroup(layers?: T[]): LayerGroup; + type LatLngBoundsExpression = LatLngBounds | LatLngBoundsLiteral; + export function latLngBounds(southWest: LatLng, northEast: LatLng): LatLngBounds; - export interface LayerGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): LayerGroup; + export function latLngBounds(southWest: LatLngLiteral, northEast: LatLngLiteral): LatLngBounds; + + export function latLngBounds(southWest: LatLngTuple, northEast: LatLngTuple): LatLngBounds; + + export function latLngBounds(latlngs: LatLngBoundsLiteral): LatLngBounds; + + export type PointTuple = [number, number]; + + export interface Point { + clone(): Point; + add(otherPoint: Point): Point; // investigate if this mutates or returns a new instance + add(otherPoint: PointTuple): Point; + subtract(otherPoint: Point): Point; + subtract(otherPoint: PointTuple): Point; + divideBy(num: number): Point; + multiplyBy(num: number): Point; + scaleBy(scale: Point): Point; + scaleBy(scale: PointTuple): Point; + unscaleBy(scale: Point): Point; + unscaleBy(scale: PointTuple): Point; + round(): Point; + floor(): Point; + ceil(): Point; + distanceTo(otherPoint: Point): Point; + distanceTo(otherPoint: PointTuple): Point; + equals(otherPoint: Point): boolean; + equals(otherPoint: PointTuple): boolean; + contains(otherPoint: Point): boolean; + contains(otherPoint: PointTuple): boolean; + toString(): string; } - export var LayerGroup: LayerGroupStatic; - export interface LayerGroup extends ILayer { - /** - * Adds the group of layers to the map. - */ - addTo(map: Map): LayerGroup; + type PointExpression = Point | PointTuple; - /** - * Adds a given layer to the group. - */ - addLayer(layer: T): LayerGroup; + export function point(x: number, y: number, round?: boolean): Point; - /** - * Removes a given layer from the group. - */ - removeLayer(layer: T): LayerGroup; + export function point(coords: PointTuple): Point; - /** - * Removes a given layer of the given id from the group. - */ - removeLayer(id: string): LayerGroup; + export function point(coords: {x: number, y: number}): Point; - /** - * Returns true if the given layer is currently added to the group. - */ - hasLayer(layer: T): boolean; + export type BoundsLiteral = Array; - /** - * Returns the layer with the given id. - */ - getLayer(id: string): T; - - /** - * Returns an array of all the layers added to the group. - */ - getLayers(): T[]; - - /** - * Removes all the layers from the group. - */ - clearLayers(): LayerGroup; - - /** - * Iterates over the layers of the group, optionally specifying context of - * the iterator function. - */ - eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; - - /** - * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). - * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s - */ - toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - - -declare namespace L { - - export interface LayersOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * - * Default value: 'topright'. - */ - position?: PositionString; - - /** - * If true, the control will be collapsed into an icon and expanded on mouse hover - * or touch. - * - * Default value: true. - */ - collapsed?: boolean; - - /** - * If true, the control will assign zIndexes in increasing order to all of its - * layers so that the order is preserved when switching them on/off. - * - * Default value: true. - */ - autoZIndex?: boolean; - - } -} - -declare namespace L { - - export interface LeafletErrorEvent extends LeafletEvent { - - /** - * Error message. - */ - message: string; - - /** - * Error code (if applicable). - */ - code: number; - } -} - -declare namespace L { - - export interface LeafletEvent { - - /** - * The event type (e.g. 'click'). - */ - type: string; - - /** - * The object that fired the event. - */ - target: any; - } -} - -declare namespace L { - - export interface LeafletGeoJSONEvent extends LeafletEvent { - - /** - * The layer for the GeoJSON feature that is being added to the map. - */ - layer: ILayer; - - /** - * GeoJSON properties of the feature. - */ - properties: any; - - /** - * GeoJSON geometry type of the feature. - */ - geometryType: string; - - /** - * GeoJSON ID of the feature (if present). - */ - id: string; - } -} - -declare namespace L { - - export interface LeafletLayerEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - } -} - -declare namespace L { - - export interface LeafletLayersControlEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - - /** - * The name of the layer that was added or removed. - */ - name: string; - } -} - -declare namespace L { - - export interface LeafletLocationEvent extends LeafletEvent { - - /** - * Detected geographical location of the user. - */ - latlng: LatLng; - - /** - * Geographical bounds of the area user is located in (with respect to the accuracy - * of location). - */ - bounds: LatLngBounds; - - /** - * Accuracy of location in meters. - */ - accuracy: number; - - /** - * Height of the position above the WGS84 ellipsoid in meters. - */ - altitude: number; - - /** - * Accuracy of altitude in meters. - */ - altitudeAccuracy: number; - - /** - * The direction of travel in degrees counting clockwise from true North. - */ - heading: number; - - /** - * Current velocity in meters per second. - */ - speed: number; - - /** - * The time when the position was acquired. - */ - timestamp: number; - - } -} - -declare namespace L { - - export interface LeafletMouseEvent extends LeafletEvent { - - /** - * The geographical point where the mouse event occured. - */ - latlng: LatLng; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map layer. - */ - layerPoint: Point; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map сontainer. - */ - containerPoint: Point; - - /** - * The original DOM mouse event fired by the browser. - */ - originalEvent: MouseEvent; - } -} - -declare namespace L { - - export interface LeafletPopupEvent extends LeafletEvent { - - /** - * The popup that was opened or closed. - */ - popup: Popup; - } -} - -declare namespace L { - - export interface LeafletDragEndEvent extends LeafletEvent { - - /** - * The distance in pixels the draggable element was moved by. - */ - distance: number; - } -} - -declare namespace L { - - export interface LeafletResizeEvent extends LeafletEvent { - - /** - * The old size before resize event. - */ - oldSize: Point; - - /** - * The new size after the resize event. - */ - newSize: Point; - } -} - -declare namespace L { - - export interface LeafletTileEvent extends LeafletEvent { - - /** - * The tile element (image). - */ - tile: HTMLElement; - - /** - * The source URL of the tile. - */ - url: string; - } -} - -declare namespace L { - - namespace LineUtil { - - /** - * Dramatically reduces the number of points in a polyline while retaining - * its shape and returns a new array of simplified points. Used for a huge performance - * boost when processing/displaying Leaflet polylines for each zoom level - * and also reducing visual noise. tolerance affects the amount of simplification - * (lesser value means higher quality but slower and with more points). Also - * released as a separated micro-library Simplify.js. - */ - export function simplify(points: Point[], tolerance: number): Point[]; - - /** - * Returns the distance between point p and segment p1 to p2. - */ - export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - - /** - * Returns the closest point from a point p on a segment p1 to p2. - */ - export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; - - /** - * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show - * polyline points that are on the screen or near, increasing performance. Returns - * either false or a length-2 array of clipped points. - */ - export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; - - } -} - -declare namespace L { - - export interface LocateOptions { - - /** - * If true, starts continous watching of location changes (instead of detecting - * it once) using W3C watchPosition method. You can later stop watching using - * map.stopLocate() method. - * - * Default value: false. - */ - watch?: boolean; - - /** - * If true, automatically sets the map view to the user location with respect - * to detection accuracy, or to world view if geolocation failed. - * - * Default value: false. - */ - setView?: boolean; - - /** - * The maximum zoom for automatic view setting when using `setView` option. - * - * Default value: Infinity. - */ - maxZoom?: number; - - /** - * Number of millisecond to wait for a response from geolocation before firing - * a locationerror event. - * - * Default value: 10000. - */ - timeout?: number; - - /** - * Maximum age of detected location. If less than this amount of milliseconds - * passed since last geolocation response, locate will return a cached location. - * - * Default value: 0. - */ - maximumAge?: number; - - /** - * Enables high accuracy, see description in the W3C spec. - * - * Default value: false. - */ - enableHighAccuracy?: boolean; - } -} - -declare namespace L { - - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - */ - function map(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - */ - function map(id: string, options?: Map.MapOptions): Map; - - - export interface MapStatic extends ClassStatic { - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: string, options?: Map.MapOptions): Map; - } - export var Map: MapStatic; - - export interface Map extends IEventPowered { - // Methods for Modifying Map State - - /** - * Sets the view of the map (geographical center and zoom) with the given - * animation options. - */ - setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets the zoom of the map. - */ - setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Increases the zoom of the map by delta (1 by default). - */ - zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Decreases the zoom of the map by delta (1 by default). - */ - zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Zooms the map while keeping a specified point on the map stationary - * (e.g. used internally for scroll zoom and double-click zoom). - */ - setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets a map view that contains the given geographical bounds with the maximum - * zoom level possible. - */ - fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; - - /** - * Sets a map view that mostly contains the whole world with the maximum zoom - * level possible. - */ - fitWorld(options?: Map.FitBoundsOptions): Map; - - /** - * Pans the map to a given center. Makes an animated pan if new center is not more - * than one screen away from the current one. - */ - panTo(latlng: LatLngExpression, options?: PanOptions): Map; - - /** - * Pans the map to the closest view that would lie inside the given bounds (if - * it's not already). - */ - panInsideBounds(bounds: LatLngBounds): Map; - - /** - * Pans the map by a given number of pixels (animated). - */ - panBy(point: Point, options?: PanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - * If options.pan is false, panning will not occur. - */ - invalidateSize(options: Map.ZoomPanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - */ - invalidateSize(animate: boolean): Map; - - /** - * Restricts the map view to the given bounds (see map maxBounds option), - * passing the given animation options through to `setView`, if required. - */ - setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; - - /** - * Tries to locate the user using Geolocation API, firing locationfound event - * with location data on success or locationerror event on failure, and optionally - * sets the map view to the user location with respect to detection accuracy - * (or to the world view if geolocation failed). See Locate options for more - * details. - */ - locate(options?: LocateOptions): Map; - - /** - * Stops watching location previously initiated by map.locate({watch: true}) - * and aborts resetting the map view if map.locate was called with {setView: true}. - */ - stopLocate(): Map; - - /** - * Destroys the map and clears all related event listeners. - */ - remove(): Map; - - // Methods for Getting Map State - - /** - * Returns the geographical center of the map view. - */ - getCenter(): LatLng; - - /** - * Returns the current zoom of the map view. - */ - getZoom(): number; - - /** - * Returns the minimum zoom level of the map. - */ - getMinZoom(): number; - - /** - * Returns the maximum zoom level of the map. - */ - getMaxZoom(): number; - - /** - * Returns the LatLngBounds of the current map view. - */ - getBounds(): LatLngBounds; - - /** - * Returns the maximum zoom level on which the given bounds fit to the map view - * in its entirety. If inside (optional) is set to true, the method instead returns - * the minimum zoom level on which the map view fits into the given bounds in its - * entirety. - */ - getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; - - /** - * Returns the current size of the map container. - */ + export interface Bounds { + extend(point: Point): this; + extend(point: PointTuple): this; + getCenter(round?: boolean): Point; + getBottomLeft(): Point; + getTopRight(): Point; getSize(): Point; + contains(otherBounds: Bounds): boolean; + contains(otherBounds: BoundsLiteral): boolean; + contains(point: Point): boolean; + contains(point: PointTuple): boolean; + intersects(otherBounds: Bounds): boolean; + intersects(otherBounds: BoundsLiteral): boolean; + overlaps(otherBounds: Bounds): boolean; + overlaps(otherBounds: BoundsLiteral): boolean; - /** - * Returns the bounds of the current map view in projected pixel coordinates - * (sometimes useful in layer and overlay implementations). - */ - getPixelBounds(): Bounds; - - /** - * Returns the projected pixel coordinates of the top left point of the map layer - * (useful in custom layer and overlay implementations). - */ - getPixelOrigin(): Point; - - // Methods for Layers and Controls - - /** - * Adds the given layer to the map. If optional insertAtTheBottom is set to true, - * the layer is inserted under all others (useful when switching base tile layers). - */ - addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; - - /** - * Removes the given layer from the map. - */ - removeLayer(layer: ILayer): Map; - - /** - * Returns true if the given layer is currently added to the map. - */ - hasLayer(layer: ILayer): boolean; - - /** - * Opens the specified popup while closing the previously opened (to make sure - * only one is opened at one time for usability). - */ - openPopup(popup: Popup): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Closes the popup previously opened with openPopup (or the given one). - */ - closePopup(popup?: Popup): Map; - - /** - * Adds the given control to the map. - */ - addControl(control: IControl): Map; - - /** - * Removes the given control from the map. - */ - removeControl(control: IControl): Map; - - // Conversion Methods - - /** - * Returns the map layer point that corresponds to the given geographical coordinates - * (useful for placing overlays on the map). - */ - latLngToLayerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map layer point. - */ - layerPointToLatLng(point: Point): LatLng; - - /** - * Converts the point relative to the map container to a point relative to the - * map layer. - */ - containerPointToLayerPoint(point: Point): Point; - - /** - * Converts the point relative to the map layer to a point relative to the map - * container. - */ - layerPointToContainerPoint(point: Point): Point; - - /** - * Returns the map container point that corresponds to the given geographical - * coordinates. - */ - latLngToContainerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map container point. - */ - containerPointToLatLng(point: Point): LatLng; - - /** - * Projects the given geographical coordinates to absolute pixel coordinates - * for the given zoom level (current zoom level by default). - */ - project(latlng: LatLngExpression, zoom?: number): Point; - - /** - * Projects the given absolute pixel coordinates to geographical coordinates - * for the given zoom level (current zoom level by default). - */ - unproject(point: Point, zoom?: number): LatLng; - - /** - * Returns the pixel coordinates of a mouse click (relative to the top left corner - * of the map) given its event object. - */ - mouseEventToContainerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the pixel coordinates of a mouse click relative to the map layer given - * its event object. - */ - mouseEventToLayerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the geographical coordinates of the point the mouse clicked on given - * the click's event object. - */ - mouseEventToLatLng(event: LeafletMouseEvent): LatLng; - - // Other Methods - - /** - * Returns the container element of the map. - */ - getContainer(): HTMLElement; - - /** - * Returns an object with different map panes (to render overlays in). - */ - getPanes(): MapPanes; - - // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? - /** - * Runs the given callback when the map gets initialized with a place and zoom, - * or immediately if it happened already, optionally passing a function context. - */ - whenReady(fn: (map: Map) => void, context?: any): Map; - - // Properties - - /** - * Map dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - /** - * Touch zoom handler. - */ - touchZoom: IHandler; - - /** - * Double click zoom handler. - */ - doubleClickZoom: IHandler; - - /** - * Scroll wheel zoom handler. - */ - scrollWheelZoom: IHandler; - - /** - * Box (shift-drag with mouse) zoom handler. - */ - boxZoom: IHandler; - - /** - * Keyboard navigation handler. - */ - keyboard: IHandler; - - /** - * Mobile touch hacks (quick tap and touch hold) handler. - */ - tap: IHandler; - - /** - * Zoom control. - */ - zoomControl: Control.Zoom; - - /** - * Attribution control. - */ - attributionControl: Control.Attribution; - - /** - * Map state options - */ - options: Map.MapOptions; - - /** - * Iterates over the layers of the map, optionally specifying context - * of the iterator function. - */ - eachLayer(fn: (layer: ILayer) => void, context?: any): Map; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Map; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; - removeEventListener(eventMap?: any, context?: any): Map; - clearAllEventListeners(): Map; - on(eventMap: any, context?: any): Map; - off(eventMap?: any, context?: any): Map; + min: Point; + max: Point; } -} -declare namespace L.Map { + type BoundsExpression = Bounds | BoundsLiteral; + + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + export function bounds(topLeft: PointTuple, bottomRight: PointTuple): Bounds; + + export function bounds(points: Array): Bounds; + + export function bounds(points: BoundsLiteral): Bounds; + + export interface Evented { + + } + + interface LayerOptions { + pane?: string; + } + + interface InteractiveLayerOptions extends LayerOptions { + interactive?: boolean; + } + + export interface Layer extends Evented { + addTo(map: Map): this; + remove(): this; + removeFrom(map: Map): this; + getPane(name?: string): HTMLElement; + + // Popup methods + bindPopup(content: string, options?: PopupOptions): this; + bindPopup(content: HTMLElement, options?: PopupOptions): this; + bindPopup(content: (layer: Layer) => Content, options?: PopupOptions): this; + bindPopup(content: Popup): this; + unbindPopup(): this; + openPopup(): this; + openPopup(latlng: LatLng): this; + openPopup(latlng: LatLngLiteral): this; + openPopup(latlng: LatLngTuple): this; + closePopup(): this; + togglePopup(): this; + isPopupOpen(): boolean; + setPopupContent(content: string): this; + setPopupContent(content: HTMLElement): this; + setPopupContent(content: Popup): this; + getPopup(): Popup; + + // Tooltip methods + bindTooltip(content: string, options?: TooltipOptions): this; + bindTooltip(content: HTMLElement, options?: TooltipOptions): this; + bindTooltip(content: (layer: Layer) => Content, options?: TooltipOptions): this; + bindTooltip(content: Tooltip, options?: TooltipOptions): this; + unbindTooltip(): this; + openTooltip(): this; + openTooltip(latlng: LatLng): this; + openTooltip(latlng: LatLngLiteral): this; + openTooltip(latlng: LatLngTuple): this; + closeTooltip(): this; + toggleTooltip(): this; + isTooltipOpen(): boolean; + setTooltipContent(content: string): this; + setTooltipContent(content: HTMLElement): this; + setTooltipContent(content: Tooltip): this; + getTooltip(): Tooltip; + + // Extension methods + onAdd(map: Map): this; + onRemove(map: Map): this; + getEvents(): {[name: string]: (event: Event) => void}; + getAttribution(): string; + beforeAdd(map: Map): this; + } + + export interface GridLayerOptions { + tileSize?: number | Point; + opacity?: number; + updateWhenIdle?: boolean; + updateWhenZooming?: boolean; + updateInterval?: number; + attribution?: string; + zIndex?: number; + bounds?: LatLngBoundsExpression; + minZoom?: number; + maxZoom?: number; + noWrap?: boolean; + pane?: string; + className?: string; + keepBuffer?: number; + } + + export interface GridLayer extends Layer { + bringToFront(): this; + bringToBack(): this; + getAttribution(): string; + getContainer(): HTMLElement; + setOpacity(opacity: number): this; + setZIndex(zIndex: number): this; + isLoading(): boolean; + redraw(): this; + getTileSize(): Point; + } + + export function gridLayer(options?: GridLayerOptions): GridLayer; + + export interface TileLayerOptions extends GridLayerOptions { + minZoom?: number; + maxZoom?: number; + maxNativeZoom?: number; + subdomains?: string | Array; + errorTileUrl?: string; + zoomOffset?: number; + tms?: boolean; + zoomReverse?: boolean; + detectRetina?: boolean; + crossOrigin?: boolean; + } + + export interface TileLayer extends GridLayer { + setUrl(url: string, noRedraw?: boolean): this; + } + + export function tileLayer(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + export interface WMSOptions extends TileLayerOptions { + layers: string; + styles?: string; + format?: string; + transparent?: boolean; + version?: string; + crs?: CRS; + uppercase?: boolean; + } + + export interface WMS extends TileLayer { + setParams(params: Object, noRedraw?: boolean): this; + } + + export namespace tileLayer { + export function wms(baseUrl: string, options: WMSOptions): WMS; + } + + export interface ImageOverlayOptions extends LayerOptions { + opacity?: number; + alt?: string; + interactive?: boolean; + attribution?: string; + crossOrigin?: boolean; + } + + export interface ImageOverlay extends Layer { + setOpacity(opacity: number): this; + bringToFront(): this; + bringToBack(): this; + setUrl(url: string): this; + } + + export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; + + export type LineCapShape = 'butt' | 'round' | 'square' | 'inherit'; + + export type LineJoinShape = 'miter' | 'round' | 'bevel' | 'inherit'; + + export type FillRule = 'nonzero' | 'evenodd' | 'inherit'; + + export interface PathOptions extends InteractiveLayerOptions { + stroke?: boolean; + color?: string; + wight?: number; + opacity?: number; + lineCap?: LineCapShape; + lineJoin?: LineJoinShape; + dashArray?: string; + dashOffset?: string; + fill?: boolean; + fillColor?: string; + fillOpacity?: number; + fillRule?: FillRule; + renderer?: Renderer; + className: string; + } + + export interface Path extends Layer { + redraw(): this; + setStyle(style: PathOptions): this; + bringToFront(): this; + bringToBack(): this; + } + + export interface PolylineOptions extends PathOptions { + smoothFactor?: number; + noClip?: boolean; + } + + export interface Polyline extends Path { + toGeoJSON(): Object; // should import GeoJSON typings + getLatLngs(): Array; + setLatLngs(latlngs: Array): this; + setLatLngs(latlngs: Array): this; + setLatLngs(latlngs: Array): this; + isEmpty(): boolean; + getCenter(): LatLng; + getBounds(): LatLngBounds; + addLatLng(latlng: LatLng): this; + addLatLng(latlng: LatLngLiteral): this; + addLatLng(latlng: LatLngTuple): this; + addLatLng(latlng: Array): this; // these three overloads aren't explicitly noted in the docs + addLatLng(latlng: Array): this; + addLatLng(latlng: Array): this; + } + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export interface Polygon extends Polyline { + toGeoJSON(): Object; // should import GeoJSON typings + } + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export interface Rectangle extends Polygon { + setBounds(latLngBounds: LatLngBounds): this; + setBounds(latLngBounds: LatLngBoundsLiteral): this; + } + + export function rectangle(latLngBounds: LatLngBounds, options?: PolylineOptions): Rectangle; + + export function rectangle(latLngBounds: LatLngBoundsLiteral, options?: PolylineOptions): Rectangle; + + export interface CircleMarkerOptions extends PathOptions { + radius?: number; + } + + export interface CircleMarker extends Path { + toGeoJSON(): Object; // should import GeoJSON typings + setLatLng(latLng: LatLng): this; + setLatLng(latLng: LatLngLiteral): this; + setLatLng(latLng: LatLngTuple): this; + getLatLng(): LatLng; + setRadius(radius: number): this; + getRadius(): number; + } + + export function circleMarker(latlng: LatLng, options?: CircleMarkerOptions): CircleMarker; + + export function circleMarker(latlng: LatLngLiteral, options?: CircleMarkerOptions): CircleMarker; + + export function circleMarker(latlng: LatLngLiteral, options?: CircleMarkerOptions): CircleMarker; + + export interface CircleOptions extends PathOptions { + radius?: number; + } + + export interface Circle extends CircleMarker { + setRadius(radius: number): this; + getRadius(): number; + getBounds(): LatLngBounds; + } + + export function circle(latlng: LatLng, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngLiteral, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngTuple, options?: CircleOptions): Circle; + + export function circle(latlng: LatLng, radius: number, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngLiteral, radius: number, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngTuple, radius: number, options?: CircleOptions): Circle; + + export interface RendererOptions extends LayerOptions { + padding?: number; + } + + export interface Renderer extends Layer {} + + export interface SVG extends Renderer {} + + type Zoom = boolean | 'center'; export interface MapOptions { - - // Map State Options - - /** - * Initial geographical center of the map. - */ - center?: LatLng; - - /** - * Initial map zoom. - */ - zoom?: number; - - /** - * Layers that will be added to the map initially. - */ - layers?: ILayer[]; - - /** - * Minimum zoom level of the map. Overrides any minZoom set on map layers. - */ - minZoom?: number; - - /** - * Maximum zoom level of the map. This overrides any maxZoom set on map layers. - */ - maxZoom?: number; - - /** - * When this option is set, the map restricts the view to the given geographical - * bounds, bouncing the user back when he tries to pan outside the view, and also - * not allowing to zoom out to a view that's larger than the given bounds (depending - * on the map size). To set the restriction dynamically, use setMaxBounds method - */ - maxBounds?: LatLngBounds; - - /** - * Coordinate Reference System to use. Don't change this if you're not sure - * what it means. - * - * Default value: L.CRS.EPSG3857. - */ - crs?: ICRS; - - // Interaction Options - - /** - * Whether the map be draggable with mouse/touch or not. - * - * Default value: true. - */ - dragging?: boolean; - - /** - * Whether the map can be zoomed by touch-dragging with two fingers. - * - * Default value: true. - */ - touchZoom?: boolean; - - /** - * Whether the map can be zoomed by using the mouse wheel. - * If passed 'center', it will zoom to the center of the view regardless of - * where the mouse was. - * - * Default value: true. - */ - scrollWheelZoom?: boolean; - - /** - * Whether the map can be zoomed in by double clicking on it and zoomed out - * by double clicking while holding shift. - * If passed 'center', double-click zoom will zoom to the center of the view - * regardless of where the mouse was. - * - * Default value: true. - */ - doubleClickZoom?: boolean; - - /** - * Whether the map can be zoomed to a rectangular area specified by dragging - * the mouse while pressing shift. - * - * Default value: true. - */ - boxZoom?: boolean; - - /** - * Enables mobile hacks for supporting instant taps (fixing 200ms click delay - * on iOS/Android) and touch holds (fired as contextmenu events). - * - * Default value: true. - */ - tap?: boolean; - - /** - * The max number of pixels a user can shift his finger during touch for it - * to be considered a valid tap. - * - * Default value: 15. - */ - tapTolerance?: number; - - /** - * Whether the map automatically handles browser window resize to update itself. - * - * Default value: true. - */ - trackResize?: boolean; - - /** - * With this option enabled, the map tracks when you pan to another "copy" of - * the world and seamlessly jumps to the original one so that all overlays like - * markers and vector layers are still visible. - * - * Default value: false. - */ - worldCopyJump?: boolean; - - /** - * Set it to false if you don't want popups to close when user clicks the map. - * - * Default value: true. - */ - closePopupOnClick?: boolean; - - // Keyboard Navigation Options - - /** - * Makes the map focusable and allows users to navigate the map with keyboard - * arrows and +/- keys. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Amount of pixels to pan when pressing an arrow key. - * - * Default value: 80. - */ - keyboardPanOffset?: number; - - /** - * Number of zoom levels to change when pressing + or - key. - * - * Default value: 1. - */ - keyboardZoomOffset?: number; - - // Panning Inertia Options - - /** - * If enabled, panning of the map will have an inertia effect where the map builds - * momentum while dragging and continues moving in the same direction for some - * time. Feels especially nice on touch devices. - * - * Default value: true. - */ - inertia?: boolean; - - /** - * The rate with which the inertial movement slows down, in pixels/second2. - * - * Default value: 3000. - */ - inertiaDeceleration?: number; - - /** - * Max speed of the inertial movement, in pixels/second. - * - * Default value: 1500. - */ - inertiaMaxSpeed?: number; - - /** - * Amount of milliseconds that should pass between stopping the movement and - * releasing the mouse or touch to prevent inertial movement. - * - * Default value: 32 for touch devices and 14 for the rest. - */ - inertiaThreshold?: number; + preferCanvas?: boolean; // Control options - - /** - * Whether the zoom control is added to the map by default. - * - * Default value: true. - */ + attributionControl?: boolean; zoomControl?: boolean; - /** - * Whether the attribution control is added to the map by default. - * - * Default value: true. - */ - attributionControl?: boolean; + // Interaction options + closePopupOnClick?: boolean; + zoomSnap?: number; + zoomDelta?: number; + trackResize?: boolean; + boxZoom?: boolean; + doubleClickZoom?: Zoom; + dragging?: boolean; + + // Map state options + crs?: CRS; + center?: LatLngExpression; + zoom?: number; + minZoom?: number; + maxZoom?: number; + layers?: Array; + maxBounds?: LatLngBoundsExpression; + renderer?: Renderer; // Animation options - - /** - * Whether the tile fade animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ fadeAnimation?: boolean; - - /** - * Whether the tile zoom animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ + markerZoomAnimation?: boolean; + transform3DLimit?: number; zoomAnimation?: boolean; - - /** - * Won't animate zoom if the zoom difference exceeds this value. - * - * Default value: 4. - */ zoomAnimationThreshold?: number; - /** - * Whether markers animate their zoom with the zoom animation, if disabled - * they will disappear for the length of the animation. By default it's enabled - * in all browsers that support CSS3 Transitions except Android. - */ - markerZoomAnimation?: boolean; + // Panning inertia options + inertia?: boolean; + inertiaDeceleration?: number; + inertiaMaxSpeed?: number; + easeLinearity?: number; + worldCopyJump?: boolean; + maxBoundsViscosity?: number; - /** - * Set it to false if you don't want the map to zoom beyond min/max zoom - * and then bounce back when pinch-zooming. - * - * Default value: true. - */ + // Keyboard navigation options + keyboard?: boolean; + keyboardPanDelta?: number; + + // Mousewheel options + scrollWheelZoom?: Zoom; + wheelDebounceTime?: number; + wheelPxPerZoomLevel?: number; + + // Touch interaction options + tap?: boolean; + tapTolerance?: number; + touchZoom?: Zoom; bounceAtZoomLimits?: boolean; } - export interface ZoomOptions { - /** - * If not specified, zoom animation will happen if the zoom origin is inside the current view. - * If true, the map will attempt animating zoom disregarding where zoom origin is. - * Setting false will make it always reset the view completely without animation. - */ - animate?: boolean; + export interface Control { + } - export interface ZoomPanOptions { - - /** - * If true, the map view will be completely reset (without any animations). - * - * Default value: false. - */ - reset?: boolean; - - /** - * Sets the options for the panning (without the zoom change) if it occurs. - */ - pan?: PanOptions; - - /** - * Sets the options for the zoom change if it occurs. - */ - zoom?: ZoomOptions; - - /** - * An equivalent of passing animate to both zoom and pan options (see below). - */ - animate?: boolean; - - /** - * If true, it will delay moveend event so that it doesn't happen many times in a row. - */ - debounceMoveend?: boolean; - - /** - * Duration of animated panning, in seconds. - */ - duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). - * 1.0 means linear animation, the less the more bowed the curve. - */ - easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - */ - noMoveStart?: boolean; + interface DivOverlayOptions { + offset?: PointExpression; + zoomAnimation?: boolean; + className?: string; + pane?: string; } - export interface FitBoundsOptions extends ZoomPanOptions { - - /** - * Sets the amount of padding in the top left corner of a map container that - * shouldn't be accounted for when setting the view to fit bounds. Useful if - * you have some control overlays on the map like a sidebar and you don't - * want them to obscure objects you're zooming to. - * - * Default value: [0, 0]. - */ - paddingTopLeft?: Point; - - /** - * The same for bottom right corner of the map. - * - * Default value: [0, 0]. - */ - paddingBottomRight?: Point; - - /** - * Equivalent of setting both top left and bottom right padding to the same value. - * - * Default value: [0, 0]. - */ - padding?: Point; - - /** - * The maximum possible zoom to use. - * - * Default value: null - */ - maxZoom?: number; + export interface PopupOptions extends DivOverlayOptions { + maxWidth?: number; + minWidth?: number; + maxHeight?: number; + autoPan?: boolean; + autoPanPaddingTopLeft?: PointExpression; + autoPanPaddingBottomRight?: PointExpression; + autoPanPadding?: PointExpression; + keepInView?: boolean; + closeButton?: boolean; + autoClose?: boolean; } -} -declare namespace L { + type Content = string | HTMLElement; - export interface MapPanes { - - /** - * Pane that contains all other map panes. - */ - mapPane: HTMLElement; - - /** - * Pane for tile layers. - */ - tilePane: HTMLElement; - - /** - * Pane that contains all the panes except tile pane. - */ - objectsPane: HTMLElement; - - /** - * Pane for overlay shadows (e.g. marker shadows). - */ - shadowPane: HTMLElement; - - /** - * Pane for overlays like polylines and polygons. - */ - overlayPane: HTMLElement; - - /** - * Pane for marker icons. - */ - markerPane: HTMLElement; - - /** - * Pane for popups. - */ - popupPane: HTMLElement; - } -} - -declare namespace L { - - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; - - var Marker: { - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - new(latlng: LatLngExpression, options?: MarkerOptions): Marker; - }; - - export interface Marker extends ILayer, IEventPowered { - /** - * Adds the marker to the map. - */ - addTo(map: Map): Marker; - - /** - * Returns the current geographical position of the marker. - */ + export interface Popup extends Layer { getLatLng(): LatLng; - - /** - * Changes the marker position to the given point. - */ - setLatLng(latlng: LatLngExpression): Marker; - - /** - * Changes the marker icon. - */ - setIcon(icon: Icon): Marker; - - /** - * Changes the zIndex offset of the marker. - */ - setZIndexOffset(offset: number): Marker; - - /** - * Changes the opacity of the marker. - */ - setOpacity(opacity: number): Marker; - - /** - * Updates the marker position, useful if coordinates of its latLng object - * were changed directly. - */ - update(): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(html: string, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(popup: Popup, options?: PopupOptions): Marker; - - /** - * Unbinds the popup previously bound to the marker with bindPopup. - */ - unbindPopup(): Marker; - - /** - * Opens the popup previously bound by the bindPopup method. - */ - openPopup(): Marker; - - /** - * Returns the popup previously bound by the bindPopup method. - */ - getPopup(): Popup; - - /** - * Closes the bound popup of the marker if it's opened. - */ - closePopup(): Marker; - - /** - * Toggles the popup previously bound by the bindPopup method. - */ - togglePopup(): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(html: string, options?: PopupOptions): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). - */ - toGeoJSON(): GeoJSON.Feature; - - /** - * Marker dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Marker; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - fire(type: string, data?: any): Marker; - addEventListener(eventMap: any, context?: any): Marker; - removeEventListener(eventMap?: any, context?: any): Marker; - clearAllEventListeners(): Marker; - on(eventMap: any, context?: any): Marker; - off(eventMap?: any, context?: any): Marker; + setLatLng(latlng: LatLngExpression): this; + getContent(): Content; + setContent(htmlContent: string): this; + setContent(htmlContent: HTMLElement): this; + setContent(htmlContent: (source: Layer) => Content): this; + getElement(): Content; + update(): void; + isOpen(): boolean; + bringToFront(): this; + bringToBack(): this; + openOn(map: Map): this; } -} -declare namespace L { + export function popup(options?: PopupOptions, source?: Layer): Popup; - export interface MarkerOptions { + export type Direction = 'right' | 'left' | 'top' | 'bottom' | 'center' | 'auto'; - /** - * Icon class to use for rendering the marker. See Icon documentation for details - * on how to customize the marker icon. - * - * Default value: new L.Icon.Default(). - */ - icon?: Icon; - - /** - * If false, the marker will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Whether the marker is draggable with mouse/touch or not. - * - * Default value: false. - */ - draggable?: boolean; - - /** - * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Text for the browser tooltip that appear on marker hover (no tooltip by default). - * - * Default value: ''. - */ - title?: string; - - /** - * Text for the alt attribute of the icon image (useful for accessibility). - * - * Default value: ''. - */ - alt?: string; - - /** - * By default, marker images zIndex is set automatically based on its latitude. - * You this option if you want to put the marker on top of all others (or below), - * specifying a high value like 1000 (or high negative value, respectively). - * - * Default value: 0. - */ - zIndexOffset?: number; - - /** - * The opacity of the marker. - * - * Default value: 1.0. - */ + export interface TooltipOptions extends DivOverlayOptions { + pane?: string; + offset?: PointExpression; + direction?: Direction; + permanent?: boolean; + sticky?: boolean; + interactive?: boolean; opacity?: number; - - /** - * If true, the marker will get on top of others when you hover the mouse over it. - * - * Default value: false. - */ - riseOnHover?: boolean; - - /** - * The z-index offset used for the riseOnHover feature. - * - * Default value: 250. - */ - riseOffset?: number; } -} -declare namespace L { + export interface Tooltip extends Layer {} - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + export function tooltip(options?: TooltipOptions, source?: Layer): Tooltip; - export interface MultiPolygonStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + export interface ZoomOptions { + animate?: boolean; } - export var MultiPolygon: MultiPolygonStatic; - - export interface MultiPolygon extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolygon; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolygon; - - /** - * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { - - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - - export interface MultiPolylineStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - } - export var MultiPolyline: MultiPolylineStatic; - - export interface MultiPolyline extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolyline; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolyline; - - /** - * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { export interface PanOptions { - - /** - * If true, panning will always be animated if possible. If false, it will not - * animate panning, either resetting the map view if panning more than a screen - * away, or just setting a new offset for the map pane (except for `panBy` - * which always does the latter). - */ animate?: boolean; - - /** - * Duration of animated panning. - * - * Default value: 0.25. - */ duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic - * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. - * - * Default value: 0.25. - */ easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - * - * Default value: false. - */ noMoveStart?: boolean; } -} -declare namespace L { + export interface ZoomPanOptions extends ZoomOptions, PanOptions {} - export interface Path extends ILayer, IEventPowered { - - /** - * Adds the layer to the map. - */ - addTo(map: Map): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(html: string, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(popup: Popup, options?: PopupOptions): Path; - - /** - * Unbinds the popup previously bound to the path with bindPopup. - */ - unbindPopup(): Path; - - /** - * Opens the popup previously bound by the bindPopup method in the given point, - * or in one of the path's points if not specified. - */ - openPopup(latlng?: LatLngExpression): Path; - - /** - * Closes the path's bound popup if it is opened. - */ - closePopup(): Path; - - /** - * Changes the appearance of a Path based on the options in the Path options object. - */ - setStyle(object: PathOptions): Path; - - /** - * Returns the LatLngBounds of the path. - */ - getBounds(): LatLngBounds; - - /** - * Brings the layer to the top of all path layers. - */ - bringToFront(): Path; - - /** - * Brings the layer to the bottom of all path layers. - */ - bringToBack(): Path; - - /** - * Redraws the layer. Sometimes useful after you changed the coordinates that - * the path uses. - */ - redraw(): Path; - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Path; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - fire(type: string, data?: any): Path; - addEventListener(eventMap: any, context?: any): Path; - removeEventListener(eventMap?: any, context?: any): Path; - clearAllEventListeners(): Path; - on(eventMap: any, context?: any): Path; - off(eventMap?: any, context?: any): Path; - } - - export namespace Path { - /** - * True if SVG is used for vector rendering (true for most modern browsers). - */ - export var SVG: boolean; - - /** - * True if VML is used for vector rendering (IE 6-8). - */ - export var VML: boolean; - - /** - * True if Canvas is used for vector rendering (Android 2). You can also force - * this by setting global variable L_PREFER_CANVAS to true before the Leaflet - * include on your page — sometimes it can increase performance dramatically - * when rendering thousands of circle markers, but currently suffers from - * a bug that causes removing such layers to be extremely slow. - */ - export var CANVAS: boolean; - - /** - * How much to extend the clip area around the map view (relative to its size, - * e.g. 0.5 is half the screen in each direction). Smaller values mean that you - * will see clipped ends of paths while you're dragging the map, and bigger values - * decrease drawing performance. - */ - export var CLIP_PADDING: number; - } -} - -declare namespace L { - - export interface PathOptions { - - /** - * Whether to draw stroke along the path. Set it to false to disable borders on - * polygons or circles. - * - * Default value: true. - */ - stroke?: boolean; - - /** - * Stroke color. - * - * Default value: '#03f'. - */ - color?: string; - - /** - * Stroke width in pixels. - * - * Default value: 5. - */ - weight?: number; - - /** - * Stroke opacity. - * - * Default value: 0.5. - */ - opacity?: number; - - /** - * Whether to fill the path with color. Set it to false to disable filling on polygons - * or circles. - */ - fill?: boolean; - - /** - * Fill color. - * - * Default value: same as color. - */ - fillColor?: string; - - /** - * Fill opacity. - * - * Default value: 0.2. - */ - fillOpacity?: number; - - /** - * A string that defines the stroke dash pattern. Doesn't work on canvas-powered - * layers (e.g. Android 2). - */ - dashArray?: string; - - /** - * A string that defines shape to be used at the end of the stroke. - * - * Default: null. - */ - lineCap?: string; - - /** - * A string that defines shape to be used at the corners of the stroke. - * - * Default: null. - */ - lineJoin?: string; - - /** - * If false, the vector will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Sets the pointer-events attribute on the path if SVG backend is used. - */ - pointerEvents?: string; - - /** - * Custom class name set on an element. - * - * Default value: ''. - */ - className?: string; - - /** - * Sets the radius of a circle marker. - */ - radius?: number; - - } -} - -declare namespace L { - - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - function point(x: number, y: number, round?: boolean): Point; - - export interface PointStatic { - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - new(x: number, y: number, round?: boolean): Point; - } - export var Point: PointStatic; - - export interface Point { - /** - * Returns the result of addition of the current and the given points. - */ - add(otherPoint: Point): Point; - - /** - * Returns the result of subtraction of the given point from the current. - */ - subtract(otherPoint: Point): Point; - - /** - * Returns the result of multiplication of the current point by the given number. - */ - multiplyBy(number: number): Point; - - /** - * Returns the result of division of the current point by the given number. If - * optional round is set to true, returns a rounded result. - */ - divideBy(number: number, round?: boolean): Point; - - /** - * Returns the distance between the current and the given points. - */ - distanceTo(otherPoint: Point): number; - - /** - * Returns a copy of the current point. - */ - clone(): Point; - - /** - * Returns a copy of the current point with rounded coordinates. - */ - round(): Point; - - /** - * Returns true if the given point has the same coordinates. - */ - equals(otherPoint: Point): boolean; - - /** - * Returns a string representation of the point for debugging purposes. - */ - toString(): string; - - /** - * The x coordinate. - */ - x: number; - - /** - * The y coordinate. - */ - y: number; - } -} - -declare namespace L { - - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - - - export interface PolygonStatic extends ClassStatic { - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - } - export var Polygon: PolygonStatic; - - export interface Polygon extends Polyline { - } -} - -declare namespace L { - - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - - export interface PolylineStatic extends ClassStatic { - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - } - export var Polyline: PolylineStatic; - - export interface Polyline extends Path { - /** - * Adds a given point to the polyline. - */ - addLatLng(latlng: LatLngExpression): Polyline; - - /** - * Replaces all the points in the polyline with the given array of geographical - * points. - */ - setLatLngs(latlngs: LatLngBoundsExpression): Polyline; - - /** - * Returns an array of the points in the path. - */ - getLatLngs(): LatLng[]; - - /** - * Allows adding, removing or replacing points in the polyline. Syntax is the - * same as in Array#splice. Returns the array of removed points (if any). - */ - spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; - - /** - * Returns the LatLngBounds of the polyline. - */ - getBounds(): LatLngBounds; - - /** - * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { - - export interface PolylineOptions extends PathOptions { - - /** - * How much to simplify the polyline on each zoom level. More means better performance - * and smoother look, and less means more accurate representation. - * - * Default value: 1.0. - */ - smoothFactor?: number; - - /** - * Disabled polyline clipping. - * - * Default value: false. - */ - noClip?: boolean; - } -} - -declare namespace L { - - namespace PolyUtil { - - /** - * Clips the polygon geometry defined by the given points by rectangular bounds. - * Used by Leaflet to only show polygon points that are on the screen or near, - * increasing performance. Note that polygon points needs different algorithm - * for clipping than polyline, so there's a seperate method for it. - */ - export function clipPolygon(points: Point[], bounds: Bounds): Point[]; - } -} - -declare namespace L { - - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - function popup(options?: PopupOptions, source?: any): Popup; - - export interface PopupStatic extends ClassStatic { - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - new(options?: PopupOptions, source?: any): Popup; - } - export var Popup: PopupStatic; - - export interface Popup extends ILayer { - /** - * Adds the popup to the map. - */ - addTo(map: Map): Popup; - - /** - * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). - */ - openOn(map: Map): Popup; - - /** - * Sets the geographical point where the popup will open. - */ - setLatLng(latlng: LatLngExpression): Popup; - - /** - * Returns the geographical point of popup. - */ - getLatLng(): LatLng; - - /** - * Sets the HTML content of the popup. - */ - setContent(html: string): Popup; - - /** - * Sets the HTML content of the popup. - */ - setContent(el: HTMLElement): Popup; - - /** - * Returns the content of the popup. - */ - getContent(): HTMLElement; - //getContent(): string; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - /** - * Updates the popup content, layout and position. Useful for updating the popup after - * something inside changed, e.g. image loaded. - */ - update(): Popup; - } -} - -declare namespace L { - - export interface PopupOptions { - - /** - * Max width of the popup. - * - * Default value: 300. - */ - maxWidth?: number; - - /** - * Min width of the popup. - * - * Default value: 50. - */ - minWidth?: number; - - /** - * If set, creates a scrollable container of the given height inside a popup - * if its content exceeds it. - */ - maxHeight?: number; - - /** - * Set it to false if you don't want the map to do panning animation to fit the opened - * popup. - * - * Default value: true. - */ - autoPan?: boolean; - - /** - * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. - */ - keepInView?: boolean; - - /** - * Controls the presense of a close button in the popup. - * - * Default value: true. - */ - closeButton?: boolean; - - /** - * The offset of the popup position. Useful to control the anchor of the popup - * when opening it on some overlays. - * - * Default value: new Point(0, 6). - */ - offset?: Point; - - /** - * The margin between the popup and the top left corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingTopLeft?: Point; - - /** - * The margin between the popup and the bottom right corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingBottomRight?: Point; - - /** - * The margin between the popup and the edges of the map view after autopanning - * was performed. - * - * Default value: new Point(5, 5). - */ - autoPanPadding?: Point; - - /** - * Whether to animate the popup on zoom. Disable it if you have problems with - * Flash content inside popups. - * - * Default value: true. - */ - zoomAnimation?: boolean; - - /** - * Set it to false if you want to override the default behavior of the popup - * closing when user clicks the map (set globally by the Map closePopupOnClick - * option). - */ - closeOnClick?: boolean; - - /** - * A custom class name to assign to the popup. - */ - className?: string; - } -} - -declare namespace L { - - export interface PosAnimationStatic extends ClassStatic { - /** - * Creates a PosAnimation object. - */ - new(): PosAnimation; - } - export var PosAnimation: PosAnimationStatic; - - export interface PosAnimation extends IEventPowered { - /** - * Run an animation of a given element to a new position, optionally setting - * duration in seconds (0.25 by default) and easing linearity factor (3rd argument - * of the cubic bezier curve, 0.5 by default) - */ - run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): PosAnimation; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - fire(type: string, data?: any): PosAnimation; - addEventListener(eventMap: any, context?: any): PosAnimation; - removeEventListener(eventMap?: any, context?: any): PosAnimation; - clearAllEventListeners(): PosAnimation; - on(eventMap: any, context?: any): PosAnimation; - off(eventMap?: any, context?: any): PosAnimation; - } -} - -declare namespace L { - - namespace Projection { - - /** - * Spherical Mercator projection — the most common projection for online maps, - * used by almost all free and commercial tile providers. Assumes that Earth - * is a sphere. Used by the EPSG:3857 CRS. - */ - export var SphericalMercator: IProjection; - - /** - * Elliptical Mercator projection — more complex than Spherical Mercator. - * Takes into account that Earth is a geoid, not a perfect sphere. Used by the - * EPSG:3395 CRS. - */ - export var Mercator: IProjection; - - /** - * Equirectangular, or Plate Carree projection — the most simple projection, - * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. - * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple - * CRS. - */ - export var LonLat: IProjection; - } -} - -declare namespace L { - - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; - - export interface RectangleStatic extends ClassStatic { - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - new(bounds: LatLngBounds, options?: PathOptions): Rectangle; - } - export var Rectangle: RectangleStatic; - - export interface Rectangle extends Polygon { - /** - * Redraws the rectangle with the passed bounds. - */ - setBounds(bounds: LatLngBounds): Rectangle; - } -} - - -declare namespace L { - - export interface ScaleOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomleft'. - */ - position?: PositionString; - - /** - * Maximum width of the control in pixels. The width is set dynamically to show - * round values (e.g. 100, 200, 500). - * Default value: 100. - */ - maxWidth?: number; - - /** - * Whether to show the metric scale line (m/km). - * Default value: true. - */ - metric?: boolean; - - /** - * Whether to show the imperial scale line (mi/ft). - * Default value: true. - */ - imperial?: boolean; - - /** - * If true, the control is updated on moveend, otherwise it's always up-to-date - * (updated on move). - * Default value: false. - */ - updateWhenIdle?: boolean; - } -} - -declare namespace L { - - export interface TileLayerStatic extends ClassStatic { - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - new(urlTemplate: string, options?: TileLayerOptions): TileLayer; - - WMS: { - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - new(baseUrl: string, options: WMSOptions): TileLayer.WMS; - }; - - Canvas: { - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - new(options?: TileLayerOptions): TileLayer.Canvas; - }; - } - export var TileLayer: TileLayerStatic; - - export interface TileLayer extends ILayer, IEventPowered { - /** - * Adds the layer to the map. - */ - addTo(map: Map): TileLayer; - - /** - * Brings the tile layer to the top of all tile layers. - */ - bringToFront(): TileLayer; - - /** - * Brings the tile layer to the bottom of all tile layers. - */ - bringToBack(): TileLayer; - - /** - * Changes the opacity of the tile layer. - */ - setOpacity(opacity: number): TileLayer; - - /** - * Sets the zIndex of the tile layer. - */ - setZIndex(zIndex: number): TileLayer; - - /** - * Causes the layer to clear all the tiles and request them again. - */ - redraw(): TileLayer; - - /** - * Updates the layer's URL template and redraws it. - */ - setUrl(urlTemplate: string): TileLayer; - - /** - * Returns the HTML element that contains the tiles for this layer. - */ - getContainer(): HTMLElement; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): TileLayer; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - fire(type: string, data?: any): TileLayer; - addEventListener(eventMap: any, context?: any): TileLayer; - removeEventListener(eventMap?: any, context?: any): TileLayer; - clearAllEventListeners(): TileLayer; - on(eventMap: any, context?: any): TileLayer; - off(eventMap?: any, context?: any): TileLayer; - } - - namespace TileLayer { - export interface WMS extends TileLayer { - /** - * Merges an object with the new parameters and re-requests tiles on the current - * screen (unless noRedraw was set to true). - */ - setParams(params: WMS, noRedraw?: boolean): WMS; - } - - export interface Canvas extends TileLayer { - /** - * You need to define this method after creating the instance to draw tiles; - * canvas is the actual canvas tile on which you can draw, tilePoint represents - * the tile numbers, and zoom is the current zoom. - */ - drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; - - /** - * Calling redraw will cause the drawTile method to be called for all tiles. - * May be used for updating dynamic content drawn on the Canvas - */ - redraw(): Canvas; - } - } - - export interface TileLayerFactory { - - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - (urlTemplate: string, options?: TileLayerOptions): TileLayer; - - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; - - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - canvas(options?: TileLayerOptions): L.TileLayer.Canvas; - } - - export var tileLayer: TileLayerFactory; -} - -declare namespace L { - - export interface TileLayerOptions { - - /** - * Minimum zoom number. - * - * Default value: 0. - */ - minZoom?: number; - - /** - * Maximum zoom number. - * - * Default value: 18. - */ + export interface FitBoundsOptions extends ZoomOptions, PanOptions { + paddingTopLeft?: PointExpression; + paddingBottomRight?: PointExpression; + padding?: PointExpression; maxZoom?: number; + } - /** - * Maximum zoom number the tiles source has available. If it is specified, - * the tiles on all zoom levels higher than maxNativeZoom will be loaded from - * maxZoom level and auto-scaled. - * - * Default value: null. - */ - maxNativeZoom?: number; + export interface LocateOptions { + watch?: boolean; + setView?: boolean; + maxZoom?: number; + timeout?: number; + maximumAge?: number; + enableHighAccuracy?: boolean; + } - /** - * Tile size (width and height in pixels, assuming tiles are square). - * - * Default value: 256. - */ - tileSize?: number; + export interface Handler { + enable(): this; + disable(): this; + enabled(): boolean; - /** - * Subdomains of the tile service. Can be passed in the form of one string (where - * each letter is a subdomain name) or an array of strings. - * - * Default value: 'abc'. - */ - subdomains?: string|string[]; + // Extension methods + addHooks(): void; + removeHooks(): void; + } - /** - * URL to the tile image to show in place of the tile that failed to load. - * - * Default value: ''. - */ - errorTileUrl?: string; + export interface Event { + type: string; + target: any; // should this be Object and have users cast? + } - /** - * e.g. "© CloudMade" — the string used by the attribution control, describes - * the layer data. - * - * Default value: ''. - */ - attribution?: string; + export interface MouseEvent extends Event { + latlng: LatLng; + layerPoint: Point; + containerPoint: Point; + originalEvent: MouseEvent; // how can I reference the global MouseEvent? + } - /** - * If true, inverses Y axis numbering for tiles (turn this on for TMS services). - * - * Default value: false. - */ - tms?: boolean; + export interface LocationEvent extends Event { + latlng: LatLng; + bounds: LatLngBounds; + accuracy: number; + altitude: number; + altitudeAccuracy: number; + heading: number; + speed: number; + timestamp: number; + } - /** - * If set to true, the tile coordinates won't be wrapped by world width (-180 - * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this - * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor - * or photo maps). - * - * Default value: false. - */ - continuousWorld?: boolean; + export interface ErrorEvent extends Event { + message: string; + code: number; + } - /** - * If set to true, the tiles just won't load outside the world width (-180 to 180 - * longitude) instead of repeating. - * - * Default value: false. - */ - noWrap?: boolean; + export interface LayerEvent extends Event { + layer: Layer; + } - /** - * The zoom number used in tile URLs will be offset with this value. - * - * Default value: 0. - */ - zoomOffset?: number; + export interface LayersControlEvent extends LayerEvent { + name: string; + } - /** - * If set to true, the zoom number used in tile URLs will be reversed (maxZoom - * - zoom instead of zoom) - * - * Default value: false. - */ - zoomReverse?: boolean; + export interface TileEvent extends Event { + tile: HTMLImageElement; + coords: Point; // apparently not a normal point, since docs say it has z (zoom) + } - /** - * The opacity of the tile layer. - * - * Default value: 1.0. - */ + export interface TileErrorEvent extends TileEvent { + error: Error; + } + + export interface ResizeEvent extends Event { + oldSize: Point; + newSize: Point; + } + + export interface GeoJSONEvent extends Event { + layer: Layer; + properties: any; // any or Object? + geometryType: string; + id: string; + } + + export interface PopupEvent extends Event { + popup: Popup; + } + + export interface TooltipEvent extends Event { + tooltip: Tooltip; + } + + export interface DragEndEvent extends Event { + distance: number; + } + + interface DefaultMapPanes { + mapPane: HTMLElement; + tilePane: HTMLElement; + overlayPane: HTMLElement; + shadowPane: HTMLElement; + markerPane: HTMLElement; + tooltipPane: HTMLElement; + popupPane: HTMLElement; + } + + export interface Map extends Evented { + getRenderer(layer: Path): Renderer; + + // Methods for layers and controls + addControl(control: Control): this; + removeControl(control: Control): this; + addLayer(layer: Layer): this; + removeLayer(layer: Layer): this; + hasLayer(layer: Layer): boolean; + eachLayer(fn: (layer: Layer) => void, context?: Object): this; + openPopup(popup: Popup): this; + openPopup(content: string, latlng: LatLng, options?: PopupOptions): this; + openPopup(content: string, latlng: LatLngLiteral, options?: PopupOptions): this; + openPopup(content: string, latlng: LatLngTuple, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLng, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLngLiteral, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLngTuple, options?: PopupOptions): this; + closePopup(popup?: Popup): this; + openTooltip(tooltip: Tooltip): this; + openTooltip(content: string, latlng: LatLng, options?: TooltipOptions): this; + openTooltip(content: string, latlng: LatLngLiteral, options?: TooltipOptions): this; + openTooltip(content: string, latlng: LatLngTuple, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLng, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLngLiteral, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLngTuple, options?: TooltipOptions): this; + closeTooltip(tooltip?: Tooltip): this; + + // Methods for modifying map state + setView(center: LatLng, zoom: number, options?: ZoomPanOptions): this; + setView(center: LatLngLiteral, zoom: number, options?: ZoomPanOptions): this; + setView(center: LatLngTuple, zoom: number, options?: ZoomPanOptions): this; + setZoom(zoom: number, options: ZoomPanOptions): this; + zoomIn(delta?: number, options?: ZoomOptions): this; + zoomOut(delta?: number, options?: ZoomOptions): this; + setZoomAround(latlng: LatLng, zoom: number, options: ZoomOptions): this; + setZoomAround(latlng: LatLngLiteral, zoom: number, options: ZoomOptions): this; + setZoomAround(latlng: LatLngTuple, zoom: number, options: ZoomOptions): this; // will the latlng version using tuple take precedence or will the point tuple version? + setZoomAround(offset: Point, zoom: number, options: ZoomOptions): this; + fitBounds(bounds: LatLngBounds, options: FitBoundsOptions): this; + fitBounds(bounds: LatLngBoundsLiteral, options: FitBoundsOptions): this; + fitWorld(options?: FitBoundsOptions): this; + panTo(latlng: LatLng, options?: PanOptions): this; + panTo(latlng: LatLngLiteral, options?: PanOptions): this; + panTo(latlng: LatLngTuple, options?: PanOptions): this; + panBy(offset: Point): this; + panBy(offset: PointTuple): this; + setMaxBounds(bounds: Bounds): this; // is this really bounds and not lanlngbounds? + setMaxBounds(bounds: BoundsLiteral): this; + setMinZoom(zoom: number): this; + setMaxZoom(zoom: number): this; + panInsideBounds(bounds: LatLngBounds, options?: PanOptions): this; + panInsideBounds(bounds: LatLngBoundsLiteral, options?: PanOptions): this; + invalidateSize(options: ZoomPanOptions): this; + invalidateSize(animate: boolean): this; + stop(): this; + flyTo(latlng: LatLng, zoom?: number, options?: ZoomPanOptions): this; + flyTo(latlng: LatLngLiteral, zoom?: number, options?: ZoomPanOptions): this; + flyTo(latlng: LatLngTuple, zoom?: number, options?: ZoomPanOptions): this; + flyToBounds(bounds: LatLngBounds, options?: FitBoundsOptions): this; + flyToBounds(bounds: LatLngBoundsLiteral, options?: FitBoundsOptions): this; + + // Other methods + addHandler(name: string, HandlerClass: () => Handler): this; // HandlerClass is actually a constructor function, is this the right way? + remove(): this; + createPane(name: string, container?: HTMLElement): HTMLElement; + getPane(pane: string): HTMLElement; + getPane(pane: HTMLElement): HTMLElement; + getPanes(): {[name: string]: HTMLElement} & DefaultMapPanes; + getContainer(): HTMLElement; + whenReady(fn: () => void, context?: Object): this; + + // Methods for getting map state + getCenter(): LatLng; + getZoom(): number; + getBounds(): LatLngBounds; + getMinZoom(): number; + getMaxZoom(): number; + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + getBoundsZoom(bounds: LatLngBoundsLiteral, inside?: boolean): number; + getSize(): Point; + getPixelBounds(): Bounds; + getPixelOrigin(): Point; + getPixelWorldBounds(zoom?: number): Bounds; + + // Conversion methods + getZoomScale(toZoom: number, fromZoom: number): number; + getScaleZoom(scale: number, fromZoom: number): number; + project(latlng: LatLng, zoom: number): Point; + project(latlng: LatLngLiteral, zoom: number): Point; + project(latlng: LatLngTuple, zoom: number): Point; + unproject(point: Point, zoom: number): LatLng; + unproject(point: PointTuple, zoom: number): LatLng; + layerPointToLatLng(point: Point): LatLng; + layerPointToLatLng(point: PointTuple): LatLng; + latLngToLayerPoint(latlng: LatLng): Point; + latLngToLayerPoint(latlng: LatLngLiteral): Point; + latLngToLayerPoint(latlng: LatLngTuple): Point; + wrapLatLng(latlng: LatLng): LatLng; + wrapLatLng(latlng: LatLngLiteral): LatLng; + wrapLatLng(latlng: LatLngTuple): LatLng; + distance(latlng1: LatLng, latlng2: LatLng): number; + distance(latlng1: LatLngLiteral, latlng2: LatLngLiteral): number; + distance(latlng1: LatLngTuple, latlng2: LatLngTuple): number; + containerPointToLayerPoint(point: Point): Point; + containerPointToLayerPoint(point: PointTuple): Point; + layerPointToContainerPoint(point: Point): Point; + layerPointToContainerPoint(point: PointTuple): Point; + latLngToContainerPoint(latlng: LatLng): Point; + latLngToContainerPoint(latlng: LatLngLiteral): Point; + latLngToContainerPoint(latlng: LatLngTuple): Point; + mouseEventToContainerPoint(ev: MouseEvent): Point; + mouseEventToLayerPoint(ev: MouseEvent): Point; + mouseEventToLatLng(ev: MouseEvent): LatLng; + + // Geolocation methods + locate(options?: LocateOptions): this; + stopLocate(): this; + + // Properties + boxZoom: Handler; + doubleClickZoom: Handler; + dragging: Handler; + keyboard: Handler; + scrollWheelZoom: Handler; + tap: Handler; + touchZoom: Handler; + } + + export function map(id: string, options?: MapOptions): Map; + + export function map(el: HTMLElement, options?: MapOptions): Map; + + export interface IconOptions extends LayerOptions { + iconUrl: string; + iconRetinaUrl?: string; + iconSize?: PointExpression; + iconAnchor?: PointExpression; + popupAnchor?: PointExpression; + shadowUrl?: string; + shadowRetinaUrl?: string; + shadowSize?: PointExpression; + shadowAnchor?: PointExpression; + className?: string; + } + + export interface Icon extends Layer { + createIcon(oldIcon?: HTMLElement): HTMLElement; + createShadow(oldIcon?: HTMLElement): HTMLElement; + } + + export namespace Icon { + export const Default: Icon; + } + + export function icon(options: IconOptions): Icon; + + export interface DivIconOptions extends LayerOptions { + html?: string; + bgPos?: PointExpression; + iconSize?: PointExpression; + iconAnchor?: PointExpression; + popupAnchor?: PointExpression; + className?: string; + } + + export interface DivIcon extends Icon {} + + export function divIcon(options: DivIconOptions): DivIcon; + + export interface MarkerOptions extends InteractiveLayerOptions { + icon?: Icon; + draggable?: boolean; + keyboard?: boolean; + title?: string; + alt?: string; + zIndexOffset?: number; opacity?: number; - - /** - * The explicit zIndex of the tile layer. Not set by default. - */ - zIndex?: number; - - /** - * If true, all the tiles that are not visible after panning are removed (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - unloadInvisibleTiles?: boolean; - - /** - * If false, new tiles are loaded during panning, otherwise only after it (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - updateWhenIdle?: boolean; - - /** - * If true and user is on a retina display, it will request four tiles of half the - * specified size and a bigger zoom level in place of one to utilize the high resolution. - * - * Default value: false. - */ - detectRetina?: boolean; - - /** - * If true, all the tiles that are not visible after panning are placed in a reuse - * queue from which they will be fetched when new tiles become visible (as opposed - * to dynamically creating new ones). This will in theory keep memory usage - * low and eliminate the need for reserving new memory whenever a new tile is - * needed. - * - * Default value: false. - */ - reuseTiles?: boolean; - - /** - * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. - */ - bounds?: LatLngBounds; - - /** - * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. - */ - [additionalKeys: string]: any; + riseOnHover?: boolean; + riseOffset?: number; } + + export interface Marker extends Layer { + getLatLng(): LatLng; + setLatLng(latlng: LatLng): this; + setLatLng(latlng: LatLngLiteral): this; + setLatLng(latlng: LatLngTuple): this; + setZIndexOffset(offset: number): this; + setIcon(icon: Icon): this; + setOpacity(opacity: number): this; + + // Properties + dragging: Handler; + } + + export function marker(latlng: LatLng, options?: MarkerOptions): Marker; + + export function marker(latlng: LatLngLiteral, options?: MarkerOptions): Marker; + + export function marker(latlng: LatLngTuple, options?: MarkerOptions): Marker; } -declare namespace L { - export interface TransformationStatic { - /** - * Creates a transformation object with the given coefficients. - */ - new(a: number, b: number, c: number, d: number): Transformation; - } - export var Transformation: TransformationStatic; - - export interface Transformation { - /** - * Returns a transformed point, optionally multiplied by the given scale. - * Only accepts real L.Point instances, not arrays. - */ - transform(point: Point, scale?: number): Point; - - /** - * Returns the reverse transformation of the given point, optionally divided - * by the given scale. Only accepts real L.Point instances, not arrays. - */ - untransform(point: Point, scale?: number): Point; - } +declare module 'leaflet' { + export = L; } - -declare namespace L { - - namespace Util { - - /** - * Merges the properties of the src object (or multiple objects) into dest object - * and returns the latter. Has an L.extend shortcut. - */ - export function extend(dest: any, ...sources: any[]): any; - - /** - * Returns a function which executes function fn with the given scope obj (so - * that this keyword refers to obj inside the function code). Has an L.bind shortcut. - */ - export function bind(fn: T, obj: any): T; - - /** - * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. - */ - export function stamp(obj: any): string; - - /** - * Returns a wrapper around the function fn that makes sure it's called not more - * often than a certain time interval time, but as fast as possible otherwise - * (for example, it is used for checking and requesting new tiles while dragging - * the map), optionally passing the scope (context) in which the function will - * be called. - */ - export function limitExecByInterval(fn: T, time: number, context?: any): T; - - /** - * Returns a function which always returns false. - */ - export function falseFn(): () => boolean; - - /** - * Returns the number num rounded to digits decimals. - */ - export function formatNum(num: number, digits: number): number; - - /** - * Trims and splits the string on whitespace and returns the array of parts. - */ - export function splitWords(str: string): string[]; - - /** - * Merges the given properties to the options of the obj object, returning the - * resulting options. See Class options. Has an L.setOptions shortcut. - */ - export function setOptions(obj: any, options: any): any; - - /** - * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} - * translates to '?a=foo&b=bar'. - */ - export function getParamString(obj: any): string; - - /** - * Simple templating facility, creates a string by applying the values of the - * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form - * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. - */ - export function template(str: string, data: any): string; - - /** - * Returns true if the given object is an array. - */ - export function isArray(obj: any): boolean; - - /** - * Trims the whitespace from both ends of the string and returns the result. - */ - export function trim(str: string): string; - - /** - * Data URI string containing a base64-encoded empty GIF image. Used as a hack - * to free memory from unused images on WebKit-powered mobile devices (by setting - * image src to this string). - */ - export var emptyImageUrl: string; - } -} - - -declare namespace L { - - export interface WMSOptions { - - /** - * (required) Comma-separated list of WMS layers to show. - * - * Default value: ''. - */ - layers?: string; - - /** - * Comma-separated list of WMS styles. - * - * Default value: 'image/jpeg'. - */ - styles?: string; - - /** - * WMS image format (use 'image/png' for layers with transparency). - * - * Default value: false. - */ - format?: string; - - /** - * If true, the WMS service will return images with transparency. - * - * Default value: '1.1.1'. - */ - transparent?: boolean; - - /** - * Version of the WMS service to use. - */ - version?: string; - - } -} - -/** - * Forces Leaflet to use the Canvas back-end (if available) for vector layers - * instead of SVG. This can increase performance considerably in some cases - * (e.g. many thousands of circle markers on the map). - */ -declare var L_PREFER_CANVAS: boolean; - -/** - * Forces Leaflet to not use touch events even if it detects them. - */ -declare var L_NO_TOUCH: boolean; - -/** - * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning - * (which may cause glitches in some rare environments) even if they're supported. - */ -declare var L_DISABLE_3D: boolean; - -declare module "leaflet" { - export = L; -} - -// vim: et ts=4 sw=4 diff --git a/mapbox/mapbox.d.ts b/mapbox/mapbox.d.ts index 9d341174ea..83e51ebf0e 100644 --- a/mapbox/mapbox.d.ts +++ b/mapbox/mapbox.d.ts @@ -3,7 +3,7 @@ // Definitions by: Maxime Fabre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// ////////////////////////////////////////////////////////////////////// ///////////////////////////// MAP OBJECT ///////////////////////////// From 549f6a3fa9c51e15d9c0529d1e0b9ca3cf059376 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Mon, 19 Sep 2016 10:09:32 +0300 Subject: [PATCH 073/154] Add svgIcon to MuiTheme (#11293) https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js#L249-L251 --- material-ui/material-ui.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2430923d9d..af69e80b1f 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -344,6 +344,9 @@ declare namespace __MaterialUI { disabledTextColor?: string; connectorLineColor?: string; }; + svgIcon?: { + color?: string, + }; table?: { backgroundColor?: string; }; From cf6fef6e8a8d68211e6d05196c658926c213e3b8 Mon Sep 17 00:00:00 2001 From: iskandersierra Date: Mon, 19 Sep 2016 09:14:34 +0200 Subject: [PATCH 074/154] Added typings for change-emitter@0.1.2 (#11295) --- change-emitter/change-emitter-tests.ts | 124 +++++++++++++++++++++++++ change-emitter/change-emitter.d.ts | 58 ++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 change-emitter/change-emitter-tests.ts create mode 100644 change-emitter/change-emitter.d.ts diff --git a/change-emitter/change-emitter-tests.ts b/change-emitter/change-emitter-tests.ts new file mode 100644 index 0000000000..379c7636a5 --- /dev/null +++ b/change-emitter/change-emitter-tests.ts @@ -0,0 +1,124 @@ +/// + +import { createChangeEmitter, ChangeEmitterOf0 } from "change-emitter"; + +function usage() { + // https://github.com/acdlite/change-emitter#usage + + const emitter = createChangeEmitter() + + // Called `listen` instead of `subscribe` to avoid confusion with observable spec + const unlisten = emitter.listen((...args) => { + console.log(args) + }) + + emitter.emit(1, 2, 3) // logs `[1, 2, 3]` + unlisten() + emitter.emit(4, 5, 6) // doesn't log +} + +function largerExample() { + // https://github.com/acdlite/change-emitter#larger-example + + const createStore = (reducer: Function, initialState: any) => { + let state = initialState + const emitter = createChangeEmitter() + + function dispatch(action: any) { + state = reducer(state, action) + emitter.emit() + return action + } + + function getState() { + return state + } + + return { + dispatch, + getState, + subscribe: emitter.listen + } + } +} + +function untypedEmitter() { + const { emit, listen } = createChangeEmitter(); + + const unlisten0 = listen(() => {/* do something */}); + const unlisten1 = listen(value => {/* do something with value */}); + const unlisten2 = listen((value1, value2) => {/* do something with values */}); + const unlistenArgs = listen((...args: any[]) => {/* do something with values */}); + + emit(); + emit("hello"); + emit("hello", "world"); + emit(1, 2, 3, 4, 5); + + unlisten0(); + unlisten1(); + unlisten2(); + unlistenArgs(); +} + +function emitterOf0Args() { + const { emit, listen }: ChangeEmitterOf0 = createChangeEmitter(); + + const unlisten = listen(() => { }); + // const unlisten = listen(value => {}); // SYNTAX ERROR + + emit(); + // emit("hello"); // SYNTAX ERROR + + unlisten(); +} + +function emitterOf1Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen(value => { value.length }); + + emit("hello"); + + unlisten(); +} + +function emitterOf2Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success) => { value.length > 0 === success }); + + emit("hello", true); + + unlisten(); +} + +function emitterOf3Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success, count) => { value.length > count === success }); + + emit("hello", true, 3); + + unlisten(); +} + +function emitterOf4Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4) => { }); + + emit("hello", true, 3, new Date()); + + unlisten(); +} + +function emitterOf5Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4, v5) => { }); + + emit("hello", true, 3, new Date(), "world"); + + unlisten(); +} diff --git a/change-emitter/change-emitter.d.ts b/change-emitter/change-emitter.d.ts new file mode 100644 index 0000000000..85abf116ed --- /dev/null +++ b/change-emitter/change-emitter.d.ts @@ -0,0 +1,58 @@ +// Type definitions for change-emitter v0.1.2 +// Project: https://github.com/acdlite/change-emitter +// Definitions by: Iskander Sierra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'change-emitter' { + + type Unlisten = () => void; + type Listener = (...args: any[]) => void; + type ListenerOf0 = () => void; + type ListenerOf1 = (value: T) => void; + type ListenerOf2 = (value1: T1, value2: T2) => void; + type ListenerOf3 = (value1: T1, value2: T2, value3: T3) => void; + type ListenerOf4 = (value1: T1, value2: T2, value3: T3, value4: T4) => void; + type ListenerOf5 = (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => void; + + interface ChangeEmitter { + listen(listener: Listener): Unlisten; + emit(...args: any[]): void; + } + + interface ChangeEmitterOf1 { + listen(listener: ListenerOf1): Unlisten; + emit(value: T): void; + } + + interface ChangeEmitterOf0 { + listen(listener: ListenerOf0): Unlisten; + emit(): void; + } + + interface ChangeEmitterOf2 { + listen(listener: ListenerOf2): Unlisten; + emit(value1: T1, value2: T2): void; + } + + interface ChangeEmitterOf3 { + listen(listener: ListenerOf3): Unlisten; + emit(value1: T1, value2: T2, value3: T3): void; + } + + interface ChangeEmitterOf4 { + listen(listener: ListenerOf4): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4): void; + } + + interface ChangeEmitterOf5 { + listen(listener: ListenerOf5): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4, value5: T5): void; + } + + export function createChangeEmitter(): ChangeEmitter; + export function createChangeEmitter(): ChangeEmitterOf1; + export function createChangeEmitter(): ChangeEmitterOf2; + export function createChangeEmitter(): ChangeEmitterOf3; + export function createChangeEmitter(): ChangeEmitterOf4; + export function createChangeEmitter(): ChangeEmitterOf5; +} From e0e86e35352adab42fe829936c199863a6e28d27 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:16:55 +0800 Subject: [PATCH 075/154] [express] http.createServer can take express app (#11292) * Create pug-test.ts * Test http.createServer can take express app * Delete this --- express/express-tests.ts | 179 +++++++++++++++++++++------------------ 1 file changed, 96 insertions(+), 83 deletions(-) diff --git a/express/express-tests.ts b/express/express-tests.ts index 439ef95012..92cef00b85 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,101 +1,114 @@ /// /// - import * as express from 'express'; -var app = express(); - -app.engine('jade', require('jade').__express); -app.engine('html', require('ejs').renderFile); - -express.static.mime.define({ - 'application/fx': ['fx'] -}); -app.use('/static', express.static(__dirname + '/public')); - -// simple logger -app.use(function(req, res, next){ - console.log('%s %s', req.method, req.url); - next(); -}); - -app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { - console.error(err); - next(err); -}); -app.get('/', function(req, res){ - res.send('hello world'); -}); +namespace express_tests { -const router = express.Router(); + var app = express(); + app.engine('jade', require('jade').__express); + app.engine('html', require('ejs').renderFile); -const pathStr : string = 'test'; -const pathRE : RegExp = /test/; -const path = true? pathStr : pathRE; + express.static.mime.define({ + 'application/fx': ['fx'] + }); + app.use('/static', express.static(__dirname + '/public')); -router.get(path); -router.put(path) -router.post(path); -router.delete(path); -router.get(pathStr); -router.put(pathStr) -router.post(pathStr); -router.delete(pathStr); -router.get(pathRE); -router.put(pathRE) -router.post(pathRE); -router.delete(pathRE); - -router.use((req, res, next) => { next(); }) -router.route('/users') - .get((req, res, next) => { - let types: string[] = req.accepts(); - let type: string | boolean = req.accepts('json'); - type = req.accepts(['json', 'text']); - type = req.accepts('json', 'text'); - - let charsets: string[] = req.acceptsCharsets(); - let charset: string | boolean = req.acceptsCharsets('utf-8'); - charset = req.acceptsCharsets(['utf-8', 'utf-16']); - charset = req.acceptsCharsets('utf-8', 'utf-16'); - - let encodings: string[] = req.acceptsEncodings(); - let encoding: string | boolean = req.acceptsEncodings('gzip'); - encoding = req.acceptsEncodings(['gzip', 'deflate']); - encoding = req.acceptsEncodings('gzip', 'deflate'); - - let languages: string[] = req.acceptsLanguages(); - let language: string | boolean = req.acceptsLanguages('en'); - language = req.acceptsLanguages(['en', 'ja']); - language = req.acceptsLanguages('en', 'ja'); - - res.send(req.query['token']); + // simple logger + app.use(function(req, res, next) { + console.log('%s %s', req.method, req.url); + next(); }); -router.get('/user/:id', function(req, res, next) { - if (req.params.id == 0) next('route'); - else next(); -}, function(req, res, next) { - res.render('regular'); -}); + app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + console.error(err); + next(err); + }); -app.use((req, res, next) => { - // hacky trick, router is just a handler - router(req, res, next); -}); -app.use(router); + app.get('/', function(req, res) { + res.send('hello world'); + }); -app.listen(3000); + const router = express.Router(); -const next: express.NextFunction = () => {}; -const nextWithArgument: express.NextFunction = (err: any) => {}; -/** - * The express.Application is compatible with http.createServer - */ + const pathStr: string = 'test'; + const pathRE: RegExp = /test/; + const path = true ? pathStr : pathRE; + router.get(path); + router.put(path) + router.post(path); + router.delete(path); + router.get(pathStr); + router.put(pathStr) + router.post(pathStr); + router.delete(pathStr); + router.get(pathRE); + router.put(pathRE) + router.post(pathRE); + router.delete(pathRE); + + router.use((req, res, next) => { next(); }) + router.route('/users') + .get((req, res, next) => { + let types: string[] = req.accepts(); + let type: string | boolean = req.accepts('json'); + type = req.accepts(['json', 'text']); + type = req.accepts('json', 'text'); + + let charsets: string[] = req.acceptsCharsets(); + let charset: string | boolean = req.acceptsCharsets('utf-8'); + charset = req.acceptsCharsets(['utf-8', 'utf-16']); + charset = req.acceptsCharsets('utf-8', 'utf-16'); + + let encodings: string[] = req.acceptsEncodings(); + let encoding: string | boolean = req.acceptsEncodings('gzip'); + encoding = req.acceptsEncodings(['gzip', 'deflate']); + encoding = req.acceptsEncodings('gzip', 'deflate'); + + let languages: string[] = req.acceptsLanguages(); + let language: string | boolean = req.acceptsLanguages('en'); + language = req.acceptsLanguages(['en', 'ja']); + language = req.acceptsLanguages('en', 'ja'); + + res.send(req.query['token']); + }); + + router.get('/user/:id', function(req, res, next) { + if (req.params.id == 0) next('route'); + else next(); + }, function(req, res, next) { + res.render('regular'); + }); + + app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); + }); + + app.use(router); + + app.listen(3000); + + const next: express.NextFunction = () => { }; +} + +/*************************** + * * + * Test with other modules * + * * + ***************************/ import * as http from 'http'; -http.createServer(app); + + +namespace node_tests { + + { + // http.createServer can take express application + const app: express.Application = express(); + http.createServer(app).listen(5678); + } +} From 6fbe7a4242ee73c416397e7d54c85f2eab0058ce Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 03:18:09 -0400 Subject: [PATCH 076/154] Implemented Proj4 definition (#11303) * Implement Proj4 definition * Add proj4 tests --- proj4/proj4-tests.ts | 50 +++++++++++++++++++ proj4/proj4.d.ts | 116 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 proj4/proj4-tests.ts create mode 100644 proj4/proj4.d.ts diff --git a/proj4/proj4-tests.ts b/proj4/proj4-tests.ts new file mode 100644 index 0000000000..c2d5a286b3 --- /dev/null +++ b/proj4/proj4-tests.ts @@ -0,0 +1,50 @@ +/// +import * as proj4 from 'proj4' + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// +const name = 'WGS84' +const epsg = { + 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', + 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', +} +const point1 = [-71, 41] +const point2 = {x: 2, y: 5} +const mgrs = "24XWT783908" + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// +proj4(epsg['4269'], epsg['4326'], point1) +proj4(epsg['4269'], point1) +proj4(epsg['4269'], epsg['4326']).forward(point2) +proj4(epsg['4269'], epsg['4326']).inverse(point2) + +/////////////////////////////////// +// Named Projections +/////////////////////////////////// +proj4.defs('WGS84', epsg['4326']) +proj4.defs([ + ['EPSG:4326', epsg['4326']], + ['EPSG:4269', epsg['4269']] +]) +proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')) + +/////////////////////////////////// +// Utils +/////////////////////////////////// +// WGS84 +proj4.WGS84 + +// Proj +proj4.Proj('WGS84') + +// toPoint +proj4.toPoint([1, 2]) +proj4.toPoint([1, 2, 3]) +proj4.toPoint([1, 2, 3, 4]) + +// Point +// WARNING: Deprecated in v3 +proj4.Point([1, 2, 3, 4]) \ No newline at end of file diff --git a/proj4/proj4.d.ts b/proj4/proj4.d.ts new file mode 100644 index 0000000000..70de08b5a6 --- /dev/null +++ b/proj4/proj4.d.ts @@ -0,0 +1,116 @@ +// Type definitions for proj4 2.3.15 +// Project: https://github.com/proj4js/proj4js +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "proj4" { + const TemplateCoordinates: Array | InterfaceCoordinates; + + interface InterfaceCoordinates { + x: number, + y: number, + z?: number, + m?: number + } + + interface InterfaceDatum { + datum_type: number + a: number + b: number + es: number + ep2: number + } + + interface Proj4Static { + forward(coordinates: typeof TemplateCoordinates): Array + inverse(coordinates: typeof TemplateCoordinates): Array + } + + interface InterfaceProjection { + title: string + projName: string + ellps: string + datumCode: string + units: string + a: number + rf: number + ellipseName: string + b: number + a2: number + b2: number + es: number + e: number + ep2: number + k0: number + axis: string + datum: InterfaceDatum + init: typeof proj4.Proj, + forward(coordinates: typeof TemplateCoordinates): Array + inverse(coordinates: typeof TemplateCoordinates): Array + names: Array + to_meter(value: number): any + from_greenwich(value: number): any + } + + namespace proj4 { + /** + * @name defaultDatum + */ + export const defaultDatum: string; + + /** + * @name Proj + */ + export function Proj(srsCode:any, callback?: any): InterfaceProjection; + + /** + * @name WGS84 + */ + export const WGS84: any; + + /** + * Depecrated v3 + * @name Point + */ + export function Point(x: number, y: number, z?: number): InterfaceCoordinates; + export function Point(coordinates: Array): InterfaceCoordinates; + export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates; + export function Point(coordinates: string): InterfaceCoordinates; + + /** + * @name toPoint + */ + export function toPoint(array: Array): InterfaceCoordinates; + + /** + * @name defs + */ + export function defs(name: string): any; + export function defs(name: string, projection: string): any; + export function defs(name: Array>): any; + + /** + * @name transform + */ + export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any; + + /** + * @name mgrs + */ + export function mgrs(coordinates: Array, accuracy: number): string; + + /** + * @name version + */ + export const version: string; + } + + /** + * @name proj4 + */ + function proj4(fromProjection: string): Proj4Static; + function proj4(fromProjection: string, toProjection: string): Proj4Static; + function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array; + function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array; + export = proj4 +} From 4fd81af1e812fc860fd7acc844f9fac5247372e6 Mon Sep 17 00:00:00 2001 From: Jay Anslow Date: Mon, 19 Sep 2016 08:18:23 +0100 Subject: [PATCH 077/154] Use bluebird@3 instead of @2 (#11299) --- fs-extra-promise/fs-extra-promise.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs-extra-promise/fs-extra-promise.d.ts b/fs-extra-promise/fs-extra-promise.d.ts index bdf8360b77..2243a4d1c5 100644 --- a/fs-extra-promise/fs-extra-promise.d.ts +++ b/fs-extra-promise/fs-extra-promise.d.ts @@ -6,7 +6,7 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts via TSD fs-extra definition /// -/// +/// declare module "fs-extra-promise" { import stream = require("stream"); From 1ce244c131e77a19c72952cab39e7deba645f6df Mon Sep 17 00:00:00 2001 From: Mitchell Wills Date: Mon, 19 Sep 2016 00:19:32 -0700 Subject: [PATCH 078/154] Correct the Angular Material IToastService updateContent typings (#11305) --- angular-material/angular-material-tests.ts | 5 ++++- angular-material/angular-material.d.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index c3ebcbaf99..552ba7a95e 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -132,7 +132,10 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { - $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!')); + $scope['openToast'] = () => { + $mdToast.show($mdToast.simple().textContent('Hello!')); + $mdToast.updateTextContent('New Content'); + } $scope['customToast'] = () => { var options = { diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 66852586da..3fa0290904 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -177,7 +177,8 @@ declare namespace angular.material { showSimple(content: string): angular.IPromise; simple(): ISimpleToastPreset; build(): IToastPreset; - updateContent(): void; + updateContent(newContent: string): void; + updateTextContent(newContent: string): void hide(response?: any): void; cancel(response?: any): void; } From 4c7b1220e0266d0f7eae7b78ecfbb0823e1d9315 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 03:22:08 -0400 Subject: [PATCH 079/154] Implemented shapefile definition (#11307) * Implement shapefile definition * Implement shapefile definition * Shapefile remove Promise reference --- shapefile/shapefile-tests.ts | 19 +++++++++++++++++++ shapefile/shapefile.d.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 shapefile/shapefile-tests.ts create mode 100644 shapefile/shapefile.d.ts diff --git a/shapefile/shapefile-tests.ts b/shapefile/shapefile-tests.ts new file mode 100644 index 0000000000..1a827d2706 --- /dev/null +++ b/shapefile/shapefile-tests.ts @@ -0,0 +1,19 @@ +/// +import * as shapefile from 'shapefile' + +shapefile.open('./example.shp') + .then(source => { + source.bbox + source.read() + .then(result => { + result.value + result.done + }) + }) + +shapefile.read("example.shp") + .then(result => { + result.bbox + result.features + result.type + }) diff --git a/shapefile/shapefile.d.ts b/shapefile/shapefile.d.ts new file mode 100644 index 0000000000..20a0b85c7b --- /dev/null +++ b/shapefile/shapefile.d.ts @@ -0,0 +1,31 @@ +// Type definitions for shapefile 0.5.6 +// Project: https://github.com/mbostock/shapefile +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const shapefile: shapefile.ShapefileStatic; + +declare namespace shapefile { + interface Options { + encoding: string + highWaterMark: number + } + interface Feature { + done: boolean + value: GeoJSON.Feature + } + interface Shapefile { + bbox: Array + read(): Promise; + } + interface ShapefileStatic { + open(shp: any, dbf?: any, options?: Options): Promise; + read(shp: any, dbf?: any, options?: Options): Promise>; + } +} + +declare module "shapefile" { + export = shapefile +} From b36bf17397d104c12df35f44b75cda262946b140 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:23:24 +0800 Subject: [PATCH 080/154] [pug] Create pug definition (#11258) * Create pug.d.ts * Create pug-test.ts * Add project in comments * Rename --- pug/pug-tests.ts | 103 +++++++++++++++++++++++++++++++++++++++++++++++ pug/pug.d.ts | 50 +++++++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 pug/pug-tests.ts create mode 100644 pug/pug.d.ts diff --git a/pug/pug-tests.ts b/pug/pug-tests.ts new file mode 100644 index 0000000000..5ba7d9ad06 --- /dev/null +++ b/pug/pug-tests.ts @@ -0,0 +1,103 @@ +/// +import * as pug from 'pug'; + + +//////////////////////////////////////////////////////////// +/// Options https://pugjs.org/api/reference.html#options /// +//////////////////////////////////////////////////////////// +namespace options_tests { + let opts: pug.Options; + let str = 'string' + let bool = false; + let strArray = ['string']; + + opts.filename = str; + + opts.basedir = str; + + opts.doctype = str; + + opts.pretty = str; + opts.pretty = bool; + + opts.filters = {}; + + opts.self = bool; + + opts.debug = bool; + opts.compileDebug = bool; + + opts.globals = strArray; + + opts.cache = bool; + + opts.inlineRuntimeFunctions = bool; + + opts.name = str; +} + +//////////////////////////////////////////////////////////// +/// Methods https://pugjs.org/api/reference.html#methods /// +//////////////////////////////////////////////////////////// +namespace methods_tests { + let source = `p #{ name } 's Pug source code!`; + let path = "foo.pug"; + let compileTemplate: pug.compileTemplate; + let template: string; + let clientFunctionString: pug.ClientFunctionString; + let str: string; + + { + /// pug.compile(source, ?options) https://pugjs.org/api/reference.html#pugcompilesource-options + compileTemplate = pug.compile(source); + template = compileTemplate(); + } + + { + /// pug.compileFile(path, ?options) https://pugjs.org/api/reference.html#pugcompilefilepath-options + compileTemplate = pug.compileFile(path); + template = compileTemplate(); + } + + { + /// pug.compileClient(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientsource-options + clientFunctionString = pug.compileClient(path); + str = pug.compileClient(path); + } + + { + /// pug.compileClientWithDependenciesTracked(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientwithdependenciestrackedsource-options + let obj = pug.compileClientWithDependenciesTracked(source); + clientFunctionString = obj.body; + str = obj.body; + let strArray: string[] = obj.dependencies; + } + + { + /// pug.compileFileClient(path, ?options) https://pugjs.org/api/reference.html#pugcompilefileclientpath-options + clientFunctionString = pug.compileFileClient(path); + str = pug.compileFileClient(path); + } + + { + /// pug.render(source, ?options, ?callback) https://pugjs.org/api/reference.html#pugrendersource-options-callback + str = pug.render(source); + + // test type for callback paraments + pug.render(source, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } + + { + /// pug.renderFile(path, ?options, ?callback) https://pugjs.org/api/reference.html#pugrenderfilepath-options-callback + str = pug.renderFile(path); + + // test type for callback paraments + pug.renderFile(path, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } +} diff --git a/pug/pug.d.ts b/pug/pug.d.ts new file mode 100644 index 0000000000..8902aa7cf4 --- /dev/null +++ b/pug/pug.d.ts @@ -0,0 +1,50 @@ +// Type definitions for pug 2.0.0-beta6 +// Project: https://github.com/pugjs/pug +// Definitions by: TonyYang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Table of Contents + * + * - Options https://pugjs.org/api/reference.html#options + * - Methods https://pugjs.org/api/reference.html#methods + * + * The order of contents is according to pugjs API document. + */ +declare module 'pug' { + //////////////////////////////////////////////////////////// + /// Options https://pugjs.org/api/reference.html#options /// + //////////////////////////////////////////////////////////// + export interface Options { + filename?: string; + basedir?: string; + doctype?: string; + pretty?: boolean | string; + filters?: any; + self?: boolean; + debug?: boolean; + compileDebug?: boolean; + globals?: string[]; + cache?: boolean; + inlineRuntimeFunctions?: boolean; + name?: string; + } + + //////////////////////////////////////////////////////////// + /// Methods https://pugjs.org/api/reference.html#methods /// + //////////////////////////////////////////////////////////// + export function compile(source: string, options?: Options): (locals?: any) => string; + export function compileFile(path: string, options?: Options): (locals?: any) => string; + export function compileClient(source: string, options?: Options): ClientFunctionString; + export function compileClientWithDependenciesTracked(source: string, options?: Options): { + body: ClientFunctionString; + dependencies: string[]; + }; + export function compileFileClient(path: string, options?: Options): ClientFunctionString; + export function render(source: string, options?: Options, callback?: (err: Error, html: string) => void): string; + export function renderFile(path: string, options?: Options, callback?: (err: Error, html: string) => void): string; + + // else + export type ClientFunctionString = string; // ex: 'function (locals) {...}' + export type compileTemplate = (locals?: any) => string; +} From 150546f73b24ed9569e22f88a28fcbaf7be51402 Mon Sep 17 00:00:00 2001 From: doronbrikman Date: Mon, 19 Sep 2016 10:23:35 +0300 Subject: [PATCH 081/154] Update enzyme.d.ts (#11252) add render method to ReactWrapper --- enzyme/enzyme.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 4a5bf2beac..31ffce8923 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -458,6 +458,7 @@ declare module "enzyme" { export interface ReactWrapper extends CommonWrapper { unmount(): ReactWrapper; mount(): ReactWrapper; + render(): CheerioWrapper; /** * Returns a wrapper of the node that matches the provided reference name. From 012b7f1072c1e9bd5d0b309b4d194a014a02ed5f Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:24:01 +0800 Subject: [PATCH 082/154] [node] Format test definition (#11308) * Format test definition in v4.x * Format test definition in v6.x --- node/node-4-tests.ts | 108 ++++++++++++------------ node/node-tests.ts | 192 +++++++++++++++++++++---------------------- 2 files changed, 150 insertions(+), 150 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 66fc18ce24..26e201c910 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -28,36 +28,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// -namespace assert_tests{ +namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -108,7 +108,7 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } - + { class Networker extends events.EventEmitter { constructor() { @@ -145,13 +145,13 @@ namespace fs_tests { var buffer: Buffer; content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', {encoding : 'utf8'}); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', {flag : 'r'}); + buffer = fs.readFileSync('testfile', { flag: 'r' }); fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } { @@ -183,7 +183,7 @@ namespace fs_tests { function bufferTests() { var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('','base64'); + var base64Buffer = new Buffer('', 'base64'); var octets: Uint8Array = null; var octetBuffer = new Buffer(octets); var sharedBuffer = new Buffer(octets.buffer); @@ -197,7 +197,7 @@ function bufferTests() { // Class Method: Buffer.from(array) { - const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -262,8 +262,8 @@ function bufferTests() { // Buffer has Uint8Array's buffer field (an ArrayBuffer). { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); } } @@ -275,14 +275,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -299,7 +299,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -324,17 +324,17 @@ namespace crypto_tests { { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } - + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { let hash: Buffer | string = hmac.read(); }); } - + { //crypto_cipher_decipher_string_test - let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); let clearText: string = "This is the clear text."; let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); let cipherText: string = cipher.update(clearText, "utf8", "hex"); @@ -399,26 +399,26 @@ namespace http_tests { } { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; - http.request({agent: false}); - http.request({agent: agent}); - http.request({agent: undefined}); + http.request({ agent: false }); + http.request({ agent: agent }); + http.request({ agent: undefined }); } - + { // Make sure .listen() and .close() retuern a Server instance http.createServer().listen(0).close().address(); net.createServer().listen(0).close().address(); } - + { var request = http.request('http://0.0.0.0'); request.once('error', function() { }); @@ -487,7 +487,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -540,7 +540,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -654,11 +654,11 @@ namespace path_tests { // } path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" }); // returns // '/home/user/dir/file.txt' @@ -724,7 +724,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -741,8 +741,8 @@ namespace readline_tests { { let stream: NodeJS.WritableStream; - let dx: number|string; - let dy: number|string; + let dx: number | string; + let dy: number | string; readline.moveCursor(stream, dx, dy); } @@ -780,7 +780,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -788,7 +788,7 @@ namespace child_process_tests { /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -namespace cluster_tests { +namespace cluster_tests  { { cluster.fork(); Object.keys(cluster.workers).forEach(key => { @@ -840,7 +840,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -918,7 +918,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 06fb4a9bf7..1fcf149e99 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -30,36 +30,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// -namespace assert_tests{ +namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -118,7 +118,7 @@ namespace events_tests { result = emitter.eventNames(); } - + { class Networker extends events.EventEmitter { constructor() { @@ -139,31 +139,31 @@ namespace fs_tests { fs.writeFile("thebible.txt", "Do unto others as you would have them do unto you.", assert.ifError); - + fs.write(1234, "test"); - + fs.writeFile("Harry Potter", "\"You be wizzing, Harry,\" jived Dumbledore.", { encoding: "ascii" }, - assert.ifError); + assert.ifError); } { var content: string; var buffer: Buffer; - + content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', {encoding : 'utf8'}); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', {flag : 'r'}); + buffer = fs.readFileSync('testfile', { flag: 'r' }); fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } - + { var errno: string; fs.readFile('testfile', (err, data) => { @@ -172,52 +172,52 @@ namespace fs_tests { } }); } - + { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); // Prints: /tmp/foo-itXde2 }); } - + { var tempDir: string; tempDir = fs.mkdtempSync('/tmp/foo-'); } - + { fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); - + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); - + fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' + recursive: true, + persistent: true, + encoding: 'utf8' }, (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); } - + { - fs.access('/path/to/folder', (err) => {}); - - fs.access(Buffer.from(''), (err) => {}); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => {}); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => {}); - + fs.access('/path/to/folder', (err) => { }); + + fs.access(Buffer.from(''), (err) => { }); + + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + fs.accessSync('/path/to/folder'); - + fs.accessSync(Buffer.from('')); - + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); } } @@ -228,7 +228,7 @@ namespace fs_tests { function bufferTests() { var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('','base64'); + var base64Buffer = new Buffer('', 'base64'); var octets: Uint8Array = null; var octetBuffer = new Buffer(octets); var sharedBuffer = new Buffer(octets.buffer); @@ -250,7 +250,7 @@ function bufferTests() { // Class Method: Buffer.from(array) { - const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -373,8 +373,8 @@ function bufferTests() { // Buffer has Uint8Array's buffer field (an ArrayBuffer). { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); } } @@ -386,14 +386,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -410,7 +410,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -430,18 +430,18 @@ function stream_readable_pipe_test() { // Simplified constructors function simplified_stream_ctor_test() { new stream.Readable({ - read: function (size) { + read: function(size) { size.toFixed(); } }); new stream.Writable({ - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -449,15 +449,15 @@ function simplified_stream_ctor_test() { }); new stream.Duplex({ - read: function (size) { + read: function(size) { size.toFixed(); }, - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -467,23 +467,23 @@ function simplified_stream_ctor_test() { }); new stream.Transform({ - transform: function (chunk, enc, cb) { + transform: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb(); }, - flush: function (cb) { + flush: function(cb) { cb() }, - read: function (size) { + read: function(size) { size.toFixed(); }, - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -499,17 +499,17 @@ namespace crypto_tests { { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } - + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { let hash: Buffer | string = hmac.read(); }); } - + { //crypto_cipher_decipher_string_test - let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); let clearText: string = "This is the clear text."; let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); let cipherText: string = cipher.update(clearText, "utf8", "hex"); @@ -574,26 +574,26 @@ namespace http_tests { } { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; - http.request({agent: false}); - http.request({agent: agent}); - http.request({agent: undefined}); + http.request({ agent: false }); + http.request({ agent: agent }); + http.request({ agent: undefined }); } - + { // Make sure .listen() and .close() retuern a Server instance http.createServer().listen(0).close().address(); net.createServer().listen(0).close().address(); } - + { var request = http.request('http://0.0.0.0'); request.once('error', function() { }); @@ -665,7 +665,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -718,7 +718,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -832,11 +832,11 @@ namespace path_tests { // } path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" }); // returns // '/home/user/dir/file.txt' @@ -902,7 +902,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -919,8 +919,8 @@ namespace readline_tests { { let stream: NodeJS.WritableStream; - let dx: number|string; - let dy: number|string; + let dx: number | string; + let dy: number | string; readline.moveCursor(stream, dx, dy); } @@ -961,7 +961,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -969,7 +969,7 @@ namespace child_process_tests { /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -namespace cluster_tests { +namespace cluster_tests  { { cluster.fork(); Object.keys(cluster.workers).forEach(key => { @@ -1021,7 +1021,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -1082,19 +1082,19 @@ namespace vm_tests { namespace timers_tests { { - let immediateId = timers.setImmediate(function(){ console.log("immediate"); }); + let immediateId = timers.setImmediate(function() { console.log("immediate"); }); timers.clearImmediate(immediateId); } { let counter = 0; - let timeout = timers.setInterval(function(){ console.log("interval"); }, 20); + let timeout = timers.setInterval(function() { console.log("interval"); }, 20); timeout.unref(); timeout.ref(); timers.clearInterval(timeout); } { let counter = 0; - let timeout = timers.setTimeout(function(){ console.log("timeout"); }, 20); + let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20); timeout.unref(); timeout.ref(); timers.clearTimeout(timeout); @@ -1124,7 +1124,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } From 4f0bb211cf6daaaa8720ca2b598683a6951f81dc Mon Sep 17 00:00:00 2001 From: Julien Sergent Date: Mon, 19 Sep 2016 10:50:50 +0200 Subject: [PATCH 083/154] Update facebook-js-sdk-tests.ts --- facebook-js-sdk/facebook-js-sdk-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/facebook-js-sdk/facebook-js-sdk-tests.ts b/facebook-js-sdk/facebook-js-sdk-tests.ts index 49e615f529..41c0eaff40 100644 --- a/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -14,6 +14,12 @@ FB.getLoginStatus(function(response: fb.AuthResponse) { console.log(response.authResponse.accessToken); }); +FB.getLoginStatus(function(response: fb.AuthResponse) { + console.log(response); + console.log(response.status); + console.log(response.authResponse.accessToken); +}, true); + FB.getAuthResponse(function(response: fb.AuthResponse) { console.log(response); console.log(response.status); From a03bb7d3be1f19d9280330297e0456e632c9b71f Mon Sep 17 00:00:00 2001 From: sumit2chauhan Date: Mon, 19 Sep 2016 14:35:01 +0530 Subject: [PATCH 084/154] There is a typescript build error in this The property " component? " in IModalSettings is repeated. --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 71ef8b7363..d6c389146b 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -329,12 +329,6 @@ declare namespace angular.ui.bootstrap { * @default false */ bindToController?: boolean; - - /** - * A string reference to the component to be rendered that is registered with Angular's compiler. - * If using a directive, the directive must have restrict: 'E' and a template or templateUrl set. - */ - component?: string; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes From 26bb1f5bc53e3ba493aa4269f94b9d3db18c32ca Mon Sep 17 00:00:00 2001 From: NoHomey Date: Mon, 19 Sep 2016 17:14:45 +0300 Subject: [PATCH 085/154] Updating jest.d.ts to be close to what @jwbay requested --- jest/jest-tests.ts | 1 + jest/jest.d.ts | 329 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 268 insertions(+), 62 deletions(-) diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index 04fba5ab09..b547bd40ad 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -1,4 +1,5 @@ /// +/// // Tests based on the Jest website jest.unmock('../sum'); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 506bd6533d..d0660193f6 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,55 +1,146 @@ // Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev +// Definitions by: Asana , Ivo Stratev , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +declare var beforeAll: jest.Lifecycle; +declare var beforeEach: jest.Lifecycle; +declare var afterAll: jest.Lifecycle; +declare var afterEach: jest.Lifecycle; +declare var describe: jest.Describe; +declare var fdescribe: jest.Describe; +declare var xdescribe: jest.Describe; +declare var it: jest.It; +declare var fit: jest.It; +declare var xit: jest.It; +declare var test: jest.It; +declare var xtest: jest.It; -declare function afterEach(fn: () => any): void; -declare function beforeEach(fn: () => any): void; -declare function describe(name: string, fn: () => any): void; declare function expect(actual: any): jest.Matchers; -declare function it(name: string, fn: () => any): void; -declare function fit(name: string, fn: () => any): void; -declare function test(name: string, fn: () => any): void; -declare function xdescribe(name: string, fn: () => any): void; -declare function xit(name: string, fn: () => any): void; +interface NodeRequire { + /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ + requireActual(moduleName: string): any; + /** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */ + requireMock(moduleName: string): any; +} declare namespace jest { - interface Matchers { - lastCalledWith(...args: any[]): boolean; - not: Matchers; - toBe(expected: any): boolean; - toBeCalled(): boolean; - toBeCalledWith(...args: any[]): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeDefined(): boolean; - toBeFalsy(): boolean; - toBeGreaterThan(expected: number): boolean; - toBeGreaterThanOrEqual(expected: number): boolean; - toBeLessThan(expected: number): boolean; - toBeLessThanOrEqual(expected: number): boolean; - toBeNull(): boolean; - toBeTruthy(): boolean; - toBeUndefined(): boolean; - toContain(expected: string): boolean; - toEqual(expected: any): boolean; - toMatch(expected: RegExp): boolean; - toMatchSnapshot(): boolean; - toThrow(): boolean; - toThrowError(expected: string | RegExp): boolean; - toThrowError(expected: TFunction): boolean; - } - - interface MockContext { - calls: any[][]; - instances: T[]; + function addMatchers(matchers: jasmine.CustomMatcherFactories): void; + /** Disables automatic mocking in the module loader. */ + function autoMockOff(): void; + /** Enables automatic mocking in the module loader. */ + function autoMockOn(): void; + /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ + function clearAllTimers(): void; + /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ + function deepUnmock(moduleName: string): void; + /** Disables automatic mocking in the module loader. */ + function disableAutomock(): void; + /** Mocks a module with an auto-mocked version when it is being required. */ + function doMock(moduleName: string): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function dontMock(moduleName: string): void; + /** Enables automatic mocking in the module loader. */ + function enableAutomock(): void; + /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation?: Function): Mock; + /** Use the automatic mocking system to generate a mocked version of the given module. */ + function genMockFromModule(moduleName: string): T; + /** Returns whether the given function is a mock function. */ + function isMockFunction(fn: any): fn is Mock; + /** Mocks a module with an auto-mocked version when it is being required. */ + function mock(moduleName: string, factory?: any, options?: MockOptions): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModuleRegistry(): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModules(): void; + /** Exhausts tasks queued by setImmediate(). */ + function runAllImmediates(): void; + /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ + function runAllTicks(): void; + /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ + function runAllTimers(): void; + /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). + * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ + function runOnlyPendingTimers(): void; + /** Explicitly supplies the mock object that the module system should return for the specified module. */ + function setMock(moduleName: string, moduleExports: T): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function unmock(moduleName: string): void; + /** Instructs Jest to use fake versions of the standard timer functions. */ + function useFakeTimers(): void; + /** Instructs Jest to use the real versions of the standard timer functions. */ + function useRealTimers(): void; + + interface MockOptions { + virtual?: boolean; } - interface Mock { + interface EmptyFunction { + (): void; + } + + interface DoneCallback { + (...args: any[]): any + fail(error?: string | { message: string }): any; + } + + interface ProvidesCallback { + (cb?: DoneCallback): any; + } + + interface Lifecycle { + (fn: ProvidesCallback): any; + } + + interface It { + (name: string, fn: ProvidesCallback): void; + only: It; + skip: It; + } + + interface Describe { + (name: string, fn: EmptyFunction): void + only: Describe; + skip: Describe; + } + + interface Matchers { + not: Matchers; + lastCalledWith(...args: any[]): void; + toBe(expected: any): void; + toBeCalled(): void; + toBeCalledWith(...args: any[]): void; + toBeCloseTo(expected: number, delta: number): void; + toBeDefined(): void; + toBeFalsy(): void; + toBeGreaterThan(expected: number): void; + toBeGreaterThanOrEqual(expected: number): void; + toBeInstanceOf(expected: any): void + toBeLessThan(expected: number): void; + toBeLessThanOrEqual(expected: number): void; + toBeNull(): void; + toBeTruthy(): void; + toBeUndefined(): void; + toContain(expected: any): void; + toEqual(expected: any): void; + toHaveBeenCalled(): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toMatch(expected: string | RegExp): void; + toMatchSnapshot(): void; + toThrow(): void; + toThrowError(error?: string | Constructable | RegExp): void; + } + + interface Constructable { + new (...args: any[]): any + } + + interface Mock extends Function { new (): T; - (...args: any[]): any; // Making Mock Callable and fixing: Value of type 'Mock' is not callable. + (...args: any[]): any; mock: MockContext; mockClear(): void; mockImplementation(fn: Function): Mock; @@ -58,31 +149,145 @@ declare namespace jest { mockReturnValue(value: any): Mock; mockReturnValueOnce(value: any): Mock; } - - function clearAllTimers(): void; - function disableAutomock(): void; - function enableAutomock(): void; - function fn(implementation?: Function): Mock; - function isMockFunction(fn: Function): boolean; - function genMockFromModule(moduleName: string): T; - function mock(moduleName: string, factory?: Function, options?: {virtual: boolean}): void; - function resetModules(): void; - function runAllTicks(): void; - function runAllTimers(): void; - function runOnlyPendingTimers(): void; - function setMock(moduleName: string, moduleExports: T): void; - function unmock(moduleName: string): void; - function useFakeTimers(): void; - function useRealTimers(): void; - // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface MockContext { + calls: any[][]; + instances: T[]; + } +} + +//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected. +//Relevant parts of Jasmine's API are below so they can be changed and removed over time. +//This file can't reference jasmine.d.ts since the globals aren't compatible. + +declare function spyOn(object: any, method: string): jasmine.Spy; +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; +/** Fails a test when called within one. */ +declare function fail(error?: any): void; +declare namespace jasmine { + var clock: () => Clock; + function any(aclass: any): Any; + function anything(): Any; + function arrayContaining(sample: any[]): ArrayContaining; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + function stringMatching(value: string | RegExp): Any; + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + } + + interface Any { + new (expectedClass: any): any; + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + interface ArrayContaining { + new (sample: any[]): any; + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Spy { + (...params: any[]): any; + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): Spy; + /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ + returnValues(...values: any[]): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ + all(): CallInfo[]; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + /** The return value of the call */ + returnValue: any; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherResult { + pass: boolean; + message: string | (() => string); + } + interface ArrayLike { length: number; [n: number]: T; } } - -interface NodeRequire { - requireActual(moduleName: string): any; - requireMock(moduleName: string): any; -} From bb5916e6451594dbc565c8877dfcbfebde1c8976 Mon Sep 17 00:00:00 2001 From: pafflique Date: Mon, 19 Sep 2016 17:51:12 +0300 Subject: [PATCH 086/154] Concat second+ parameter can be plain value. --- lodash/lodash.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index eb24793955..3bdd09fab4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -501,7 +501,7 @@ declare module _ { * console.log(array); * // => [1] */ - concat(...values: (T[]|List)[]) : T[]; + concat(array: T[]|List, ...values: (T|T[]|List)[]) : T[]; } //_.difference From 20bcf21d905410c359268df715a7c6a7771493b6 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 13:28:14 -0400 Subject: [PATCH 087/154] Removed extra constants Proj4 Projection --- proj4/proj4.d.ts | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/proj4/proj4.d.ts b/proj4/proj4.d.ts index 70de08b5a6..d59063f51b 100644 --- a/proj4/proj4.d.ts +++ b/proj4/proj4.d.ts @@ -27,29 +27,15 @@ declare module "proj4" { } interface InterfaceProjection { - title: string - projName: string - ellps: string - datumCode: string - units: string - a: number - rf: number - ellipseName: string + datum: string b: number - a2: number - b2: number + rf: number + sphere: number es: number e: number ep2: number - k0: number - axis: string - datum: InterfaceDatum - init: typeof proj4.Proj, forward(coordinates: typeof TemplateCoordinates): Array inverse(coordinates: typeof TemplateCoordinates): Array - names: Array - to_meter(value: number): any - from_greenwich(value: number): any } namespace proj4 { From 2ff803ff9187fc4837a79924435f2d98f8a3bdda Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:14:41 +0200 Subject: [PATCH 088/154] refactored: randomColor to randomcolor --- randomColor/randomColor.d.ts | 2 +- randomcolor/randomcolor-tests.ts | 40 ++++++++++++++++++++++++++++++++ randomcolor/randomcolor.d.ts | 28 ++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 randomcolor/randomcolor-tests.ts create mode 100644 randomcolor/randomcolor.d.ts diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index 1c52f39be1..a92af51453 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -23,6 +23,6 @@ interface randomColorOptions { declare var randomColor: RandomColor.RandomColorStatic; -declare module 'randomColor' { +declare module 'randomcolor' { export = randomColor; } \ No newline at end of file diff --git a/randomcolor/randomcolor-tests.ts b/randomcolor/randomcolor-tests.ts new file mode 100644 index 0000000000..69b617615e --- /dev/null +++ b/randomcolor/randomcolor-tests.ts @@ -0,0 +1,40 @@ +/// + +// Returns a hex code for an attractive color +randomColor(); + +// Returns an array of ten green colors +randomColor({ + count: 10, + hue: 'green' +}); + +// Returns a hex code for a light blue +randomColor({ + luminosity: 'light', + hue: 'blue' +}); + +// Returns a hex code for a 'truly random' color +randomColor({ + luminosity: 'random', + hue: 'random' +}); + +// Returns a bright color in RGB +randomColor({ + luminosity: 'bright', + format: 'rgb' // e.g. 'rgb(225,200,20)' +}); + +// Returns a dark RGB color with random alpha +randomColor({ + luminosity: 'dark', + format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)' +}); + +// Returns a light HSL color with random alpha +randomColor({ + luminosity: 'light', + format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' +}); \ No newline at end of file diff --git a/randomcolor/randomcolor.d.ts b/randomcolor/randomcolor.d.ts new file mode 100644 index 0000000000..a92af51453 --- /dev/null +++ b/randomcolor/randomcolor.d.ts @@ -0,0 +1,28 @@ +// Type definitions for randomColor 0.4.1 +// Project: https://github.com/davidmerfield/randomColor +// Definitions by: Mathias Feitzinger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace RandomColor { + + interface RandomColorStatic { + + () : string; + + (options : randomColorOptions): string; +} + +interface randomColorOptions { + hue? : string; + luminosity? : string; + count? : string | number; + seed?: string; + format?: string; + } +} + +declare var randomColor: RandomColor.RandomColorStatic; + +declare module 'randomcolor' { + export = randomColor; +} \ No newline at end of file From 8571feee2f68b8971ee02acbe60021d368ba4136 Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:18:33 +0200 Subject: [PATCH 089/154] fixed wrong reference path --- randomColor/randomColor-tests.ts | 2 +- randomcolor/randomcolor-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts index 69b617615e..4dfd6bed26 100644 --- a/randomColor/randomColor-tests.ts +++ b/randomColor/randomColor-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Returns a hex code for an attractive color randomColor(); diff --git a/randomcolor/randomcolor-tests.ts b/randomcolor/randomcolor-tests.ts index 69b617615e..4dfd6bed26 100644 --- a/randomcolor/randomcolor-tests.ts +++ b/randomcolor/randomcolor-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Returns a hex code for an attractive color randomColor(); From 24c81fd722b734b793ea7acd7aca0fddebe47c71 Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:36:32 +0200 Subject: [PATCH 090/154] fixed renaming folder --- {randomColor => randomcolor}/randomColor-tests.ts | 0 {randomColor => randomcolor}/randomColor.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {randomColor => randomcolor}/randomColor-tests.ts (100%) rename {randomColor => randomcolor}/randomColor.d.ts (100%) diff --git a/randomColor/randomColor-tests.ts b/randomcolor/randomColor-tests.ts similarity index 100% rename from randomColor/randomColor-tests.ts rename to randomcolor/randomColor-tests.ts diff --git a/randomColor/randomColor.d.ts b/randomcolor/randomColor.d.ts similarity index 100% rename from randomColor/randomColor.d.ts rename to randomcolor/randomColor.d.ts From 66c9d1c4ba7246540618d831355eaf2ced60d48e Mon Sep 17 00:00:00 2001 From: Marc Date: Mon, 19 Sep 2016 14:56:14 -0400 Subject: [PATCH 091/154] Fix asked by andy-ms --- requirejs/require.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 1c5b4088c1..ac116494f3 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -206,7 +206,7 @@ interface RequireConfig { * } * }); **/ - urlArgs?: string | { (id: string, url: string): string; }; + urlArgs?: string | ((id: string, url: string) => string); /** * Specify the value for the type="" attribute used for script From 0a9c6b435c24fa0f07a62beb2c7d43b98914bc21 Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 20 Sep 2016 00:24:55 +0200 Subject: [PATCH 092/154] added typings for parse-mockdb --- parse-mockdb/parse-mockdb-tests.ts | 25 +++++++++++++++++++++++++ parse-mockdb/parse-mockdb.d.ts | 21 +++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 parse-mockdb/parse-mockdb-tests.ts create mode 100644 parse-mockdb/parse-mockdb.d.ts diff --git a/parse-mockdb/parse-mockdb-tests.ts b/parse-mockdb/parse-mockdb-tests.ts new file mode 100644 index 0000000000..89f586d9e8 --- /dev/null +++ b/parse-mockdb/parse-mockdb-tests.ts @@ -0,0 +1,25 @@ +/// + +ParseMockDB.mockDB(); // Mock the Parse RESTController + +// from parse-mockdb test suite +ParseMockDB.registerHook("Foo", "beforeSave", (request) => { + const object = request.object; + if (object.get('error')) { + return Parse.Promise.error('whoah'); + } + object.set('cool', true); + return Parse.Promise.as(object); +}); + +// from parse-mockdb test suite +ParseMockDB.registerHook("Foo", "beforeDelete", (request) => { + const object = request.object; + if (object.get('error')) { + return Parse.Promise.error('whoah'); + } + return Parse.Promise.as({}); +}); + +ParseMockDB.cleanUp(); // Clear the Database +ParseMockDB.unMockDB(); // Un-mock the Parse RESTController diff --git a/parse-mockdb/parse-mockdb.d.ts b/parse-mockdb/parse-mockdb.d.ts new file mode 100644 index 0000000000..c6b6e729d1 --- /dev/null +++ b/parse-mockdb/parse-mockdb.d.ts @@ -0,0 +1,21 @@ +// Type definitions for parse-mockdb v0.1.13 +// Project: https://github.com/HustleInc/parse-mockdb +// Definitions by: David Poetzsch-Heffter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ParseMockDB { + function mockDB(): void; + function unMockDB(): void; + function cleanUp(): void; + + function promiseResultSync(promise: Parse.IPromise): T; + + type HookType = "beforeSave" | "beforeDelete"; + function registerHook(className: string, hookType: HookType, hookFn: (request: Parse.Cloud.BeforeSaveRequest) => Parse.IPromise): void; +} + +declare module "parse-mockdb" { + export = ParseMockDB; +} From e822a596e4a68bd8a7e4a9f49f2ea95f6c25972d Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:54:46 -0400 Subject: [PATCH 093/154] Replace deprecated module keyword --- twilio/twilio.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index d6c2dfebf7..d6af461760 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -16,7 +16,7 @@ declare interface twilio { (sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient; } -declare module twilio { +declare namespace twilio { // Composite Classes: //============================== @@ -166,7 +166,7 @@ declare module twilio { clientName: string; outgoingScopeParams: any; scopeParams: any; - + constructor(sid?: string, tkn?: string); allowClientIncoming(clientName: string): Capability; @@ -319,7 +319,7 @@ declare module twilio { allowWorkerActivityUpdates(): void; allowWorkerFetchAttributes(): void; allowTaskReservationUpdates(): void; - + addPolicy(url: string, method: string, allowed?: boolean, queryFilter?: any, postFilter?: any): void; allow(url: string, method: string, queryFilter?: any, postFilter?: any): void; deny(url: string, method: string, queryFilter?: any, postFilter?: any): void; @@ -380,7 +380,7 @@ declare module twilio { } export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - + export interface TwimlCallback { (node?: Node): void; } export class Node implements NodeOptions { @@ -435,7 +435,7 @@ declare module twilio { export interface WebhookExpressOptions { // The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options url?: string; - + // manually specify the host name used by Twilio in a number's webhook config host?: string; From d705c4e9da0030cc11387bca31e42ddc7809ff04 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:55:03 -0400 Subject: [PATCH 094/154] Add missing `webhook()` signature --- twilio/twilio-tests.ts | 2 +- twilio/twilio.d.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 30e9892078..d7f2c60993 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -228,5 +228,5 @@ twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN'); twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN', {}); twilio.webhook({ validate: false }); - +twilio.webhook("MYAUTHTOKEN", { validate: false }); diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index d6af461760..8bd6911113 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -446,7 +446,8 @@ declare namespace twilio { // For interop with node middleware chains export interface MiddlewareFunction { (request: Http.ClientRequest, response: Http.ClientResponse, next: MiddlewareFunction): void; } - export function webhook(options?: string | webhookOptions): MiddlewareFunction; + export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; + export function webhook(options?: webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; From 6164f95bb173936a3a10396a01a30242ebc54bfa Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:58:03 -0400 Subject: [PATCH 095/154] Fix MiddlewareFunction interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Change client request/response to server request/response, because the client ones are for when node is acting as a client (making outgoing requests), whereas here it’s acting as a server. This change is needed to work with express. 2. Change the `next` argument, because next (in express) is a function called with 0 or 1 arguments, where that argument can be an any (for the error). Next is decidedly *not* a function with the MiddlewareFunction signature. 3. Import express with a capital E, for consistency with Http, since we’re using it for its namespace. --- twilio/twilio.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8bd6911113..a13352b213 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -7,7 +7,7 @@ /// /// -import * as express from 'express'; +import * as Express from 'express'; import * as Http from 'http'; import q = require('q'); @@ -444,13 +444,13 @@ declare namespace twilio { } // For interop with node middleware chains - export interface MiddlewareFunction { (request: Http.ClientRequest, response: Http.ClientResponse, next: MiddlewareFunction): void; } + export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; export function webhook(options?: webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; - export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; + export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; /// resources/Accounts.js export interface OutgoingCallerIdInstance extends InstanceResource { From ae92456e05814ba09d5d8d6770d17048dbb960e4 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 13 Sep 2016 16:47:05 -0400 Subject: [PATCH 096/154] In TwimlCallback, Node shouldn't be optional Because the callback is always called with the Node. This change is based on the advice here: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/decla ration%20files/Do's%20and%20Don'ts.md#optional-parameters-in-callbacks --- twilio/twilio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index a13352b213..84c0d02394 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -381,7 +381,7 @@ declare namespace twilio { export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - export interface TwimlCallback { (node?: Node): void; } + export interface TwimlCallback { (node: Node): void; } export class Node implements NodeOptions { name: string; From 3d032bd51037f5edfd008c1cfb3acf96a11138a1 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 13 Sep 2016 17:02:08 -0400 Subject: [PATCH 097/154] Split up TwimlMethod signature By splitting up the union into an overload, we get much more useful typing than just (any, any) --- twilio/twilio.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 84c0d02394..8d5c44984b 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -379,7 +379,10 @@ declare namespace twilio { legalNodes: Array; } - export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } + export interface TwimlMethod { + (arg1: TwimlCallback | string, arg2?: any): Node + (arg1: any, arg2?: TwimlCallback | string): Node + } export interface TwimlCallback { (node: Node): void; } From 92b719193832e5f4bcfdb529187176de675860ff Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 19:00:58 -0400 Subject: [PATCH 098/154] Allow TwimlMethods with no arguments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit E.g. hangup() doesn’t take any arguments. --- twilio/twilio-tests.ts | 2 ++ twilio/twilio.d.ts | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index d7f2c60993..1fb9afa0a4 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -212,6 +212,8 @@ resp.say('Your conference call is starting.', }); }); +resp.hangup(); + /// Capabilities var capability = new twilio.Capability(str, str); capability.allowClientIncoming('jenny'); diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8d5c44984b..c0f16211f5 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -380,8 +380,9 @@ declare namespace twilio { } export interface TwimlMethod { - (arg1: TwimlCallback | string, arg2?: any): Node - (arg1: any, arg2?: TwimlCallback | string): Node + (): Node; + (arg1: TwimlCallback | string, arg2?: any): Node; + (arg1: any, arg2?: TwimlCallback | string): Node; } export interface TwimlCallback { (node: Node): void; } From 895592ef94f5d192e3f861646d258d5362c1b8ce Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 19 Sep 2016 20:11:18 -0400 Subject: [PATCH 099/154] fixes model.discriminator() signature fixes #11323 fixes #10878 --- mongoose/mongoose-tests.ts | 15 +++++++++++++-- mongoose/mongoose.d.ts | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 5feb08b446..03dde5759b 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1124,7 +1124,6 @@ MongoModel.create([{ type: 'jelly bean' }, { arg[0].save(); arg[1].save(); }); -MongoModel.discriminator('M', new mongoose.Schema({name: String})); MongoModel.distinct('url', { clicks: {$gt: 100}}, function (err, result) { }); MongoModel.distinct('url').exec(cb); @@ -1386,4 +1385,16 @@ Final2.staticMethod(); Final2.staticProp; var final2 = new Final2(); final2.prop; -final2.method; \ No newline at end of file +final2.method; +interface ibase extends mongoose.Document { + username: string; +} +interface extended extends ibase { + email: string; +} +const base: mongoose.Model = mongoose.model('testfour', null) +const extended: mongoose.Model = base.discriminator('extendedS', null); +const x = new extended({ + username: 'hi', // required in baseSchema + email: 'beddiw', // required in extededSchema +}) \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 2d0046ea8c..6456fdc003 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2119,7 +2119,7 @@ declare module "mongoose" { * @param name discriminator model name * @param schema discriminator model schema */ - discriminator(name: string, schema: Schema): T; + discriminator(name: string, schema: Schema): Model; /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ distinct(field: string, callback?: (err: any, res: any[]) => void): Query; From b434572f41b4d9e734a2322209f08d1384dca83c Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 23:04:50 -0400 Subject: [PATCH 100/154] fixup tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Note that these tests aren’t currently passing on master either; the last PR only passed because travis didn’t actually run the tests: https://travis-ci.org/DefinitelyTyped/DefinitelyTyped/builds/160110579 --- twilio/twilio-tests.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 1fb9afa0a4..25c6915068 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -1,4 +1,5 @@ import * as twilio from './twilio'; +import * as Express from "express"; // Examples taken from https://twilio.github.io/twilio-node/ (v2.1.0) @@ -227,8 +228,12 @@ var token = capability.generate(120); /// Utilities twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val' }); -twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN'); -twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN', {}); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN'); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN', {}); twilio.webhook({ validate: false }); twilio.webhook("MYAUTHTOKEN", { validate: false }); + +function getMockExpressRequest(): Express.Request { + return JSON.parse("{}"); +} From 6ce6486f526de4709114458fb4362303c7658659 Mon Sep 17 00:00:00 2001 From: danderson00 Date: Mon, 19 Sep 2016 22:30:59 -0700 Subject: [PATCH 101/154] Update to 3.0.0 --- azure-mobile-apps/azure-mobile-apps-tests.ts | 39 +++++++++--- azure-mobile-apps/azure-mobile-apps.d.ts | 66 ++++++++++++++------ 2 files changed, 77 insertions(+), 28 deletions(-) diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 302f732889..f8f3bcef52 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -8,7 +8,7 @@ import queries = require('azure-mobile-apps/src/query'); var app = express(), mobileApp = mobileApps(); -// various configuration permutations +// various configuration permutations mobileApps({ debug: true, data: { @@ -17,7 +17,8 @@ mobileApps({ user: '', database: '', password: '' - } + }, + webhook: { url: 'http://localhost/' } }); mobileApps({ @@ -29,7 +30,7 @@ mobileApps({ // it would be nice to integrate with winston mobileApps({ logging: { level: 'silly', transports: [{}] } }) -// various custom middleware syntaxes +// various custom middleware syntaxes mobileApp.use(function (req: any, res: any, next: any) { next(); }); mobileApp.use([function () {}, function () {}]); mobileApp.use(function () {}, function () {}); @@ -43,6 +44,9 @@ mobileApp.tables.import('tables'); mobileApp.api.add('api', { authorize: true, get: function () {}, delete: function () {} }); mobileApp.api.import('api'); +// ensure the mobile app instance can be correctly mounted as an express router +app.use(mobileApp); + // Express.Table, instantiated from the mobile app var table = mobileApp.table() table.use(function (req: Express.Request, res: Express.Response, next: any) { @@ -61,16 +65,18 @@ table.read(function (context: Azure.MobileApps.Context) { table.insert(function (context: Azure.MobileApps.Context) { context.query.id = 'anotherId'; context.query.single = true; - context.item.userId = context.user.id; + context.item.userId = context.user.id; context.push.send('tag', {}, function (error, result) {}); context.push.gcm.send('tag', {}, function (error, result) {}); context.push.apns.send('tag', { payload: { } }, function (error, result) {}); context.push.wns.sendToastText01('tag', '', { headers: { } }, function (error, result) {}); + context.next(new Error()); + context.next('An error occurred'); }); table.read.use(function () {}); table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); -table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.use(function () {}).use(function () {}).read(function () {}).use(function () {}); table.access = undefined; table.access = 'authenticated'; @@ -79,10 +85,25 @@ table.update.access = 'disabled'; table.delete.access = 'authenticated'; table.insert.access = 'authenticated'; +table.filters = [function (query, context) { }]; +table.transforms = [function (item, context) { }]; +table.hooks = [function (results, context) { }]; + +table.perUser = true; +table.recordsExpire = { milliseconds: 1, seconds: 1, minutes: 1, hours: 1, days: 1, weeks: 1, months: 1, years: 1 }; +table.webhook = { url: 'http://localhost/' } +table.webhook = true; + // Express.Table, instantiated from the static require('azure-mobile-apps').table() // This is going to be interesting if we ever support more than one provider var table2 = mobileApps.table(); -table2.read(function (context: Azure.MobileApps.Context) {}) +table2.read(function (context: Azure.MobileApps.Context) {}); + +// ApiDefinition, from the static require('azure-mobile-apps').api() +var api2 = mobileApps.api({ + get: function (req, res, next) { } +}); +api2.post = function (req, res, next) {}; // Logger logger.silly('test', 'message'); @@ -90,10 +111,10 @@ logger.error('Something happened', new Error()); mobileApps.logger.debug('a debug message') // Query -queries.create('table').where({ x: 10 }).select('col1,col2'); +queries.create('table').where({ x: 10 }).select('col1,col2').includeDeleted().includeTotalCount(); mobileApps.query.create('table'); -// custom sql query +// Custom SQL query mobileApp.api.add('query', { authorize: true, get: (req, res, next) => { req.azureMobile.data.execute({ sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete", @@ -101,4 +122,4 @@ mobileApp.api.add('query', { authorize: true, get: (req, res, next) => { { name: 'complete', value: 1 } ] }).then(x => {}); -}, delete: function () {} }); +}, delete: function () {} }); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index a17e41e2d6..4731d91eb2 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -1,4 +1,4 @@ -// Type definitions for azure-mobile-apps v2.0.0-beta3 +// Type definitions for azure-mobile-apps v2.1.7 // Project: https://github.com/Azure/azure-mobile-apps-node/ // Definitions by: Microsoft Azure // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,6 +10,7 @@ declare module "azure-mobile-apps" { interface AzureMobileApps { (configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp; table(): Azure.MobileApps.Platforms.Express.Table; + api(definition?: Azure.MobileApps.ApiDefinition): Azure.MobileApps.ApiDefinition; logger: Azure.MobileApps.Logger; query: Azure.MobileApps.Query; } @@ -31,7 +32,7 @@ declare namespace Azure.MobileApps { // the additional Platforms namespace is required to avoid collisions with the main Express namespace export module Platforms { export module Express { - interface MobileApp { + interface MobileApp extends Middleware { configuration: Configuration; tables: Tables; table(): Table; @@ -45,15 +46,7 @@ declare namespace Azure.MobileApps { import(fileOrFolder: string): void; } - interface Table { - authorize?: boolean; - access?: AccessType; - autoIncrement?: boolean; - dynamicSchema?: boolean; - name: string; - columns?: any; - schema: string; - + interface Table extends TableDefinition { use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; read: TableOperation; @@ -67,11 +60,9 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; - access: AccessType; + access?: AccessType; } - type AccessType = 'anonymous' | 'authenticated' | 'disabled'; - interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; @@ -136,6 +127,7 @@ declare namespace Azure.MobileApps { auth?: Configuration.Auth; cors?: Configuration.Cors; notifications?: Configuration.Notifications; + webhook?: Webhook; } export module Configuration { @@ -152,6 +144,7 @@ declare namespace Azure.MobileApps { options?: { encrypt: boolean }; schema?: string; dynamicSchema?: boolean; + filename?: string; } interface Auth { @@ -167,8 +160,9 @@ declare namespace Azure.MobileApps { interface LoggingTransport { } interface Cors { + exposeHeaders: string; maxAge?: number; - origins: string[]; + hostnames: string[]; } interface Notifications { @@ -188,7 +182,8 @@ declare namespace Azure.MobileApps { } interface QueryJs { - includeTotalCount?: boolean; + includeTotalCount(): QueryJs; + includeDeleted(): QueryJs; orderBy(properties: string): QueryJs; orderByDescending(properties: string): QueryJs; select(properties: string): QueryJs; @@ -213,6 +208,7 @@ declare namespace Azure.MobileApps { // general var nh: Azure.ServiceBus.NotificationHubService; + interface Context { query: QueryJs; id: string | number; @@ -225,6 +221,7 @@ declare namespace Azure.MobileApps { push: typeof nh; logger: Logger; execute(): Thenable; + next(error: string|Error): any; } interface ContextData { @@ -240,15 +237,46 @@ declare namespace Azure.MobileApps { interface SqlParameterDefinition { name: string; value: any; - } + } interface TableDefinition { + access?: AccessType; authorize?: boolean; autoIncrement?: boolean; - dynamicSchema?: boolean; - name?: string; columns?: any; + databaseTableName?: string; + dynamicSchema?: boolean; + maxTop?: number; + name?: string; + pageSize?: number; schema?: string; + softDelete?: boolean; + userIdColumn?: string; + + filters?: [(QueryJs, Context) => void | QueryJs]; + transforms?: [(any, Context) => void | any]; + hooks?: [(any, Context) => void]; + + perUser?: boolean; + recordsExpire?: Duration; + webhook?: Webhook | boolean; + } + + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + + interface Duration { + milliseconds?: number; + seconds?: number; + minutes?: number; + hours?: number; + days?: number; + weeks?: number; + months?: number; + years?: number; + } + + interface Webhook { + url: string; } interface ApiDefinition { From 4b32d529eba572b91620986d3193e60d77f65c63 Mon Sep 17 00:00:00 2001 From: akankov Date: Tue, 20 Sep 2016 12:48:54 +0700 Subject: [PATCH 102/154] fromData type fix --- dropzone/dropzone.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 7464151b3b..ff8412b0e8 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -95,8 +95,8 @@ interface DropzoneOptions { uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void; totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void; - sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; success?(file: DropzoneFile, response: Object|string): void; successmultiple?(files:DropzoneFile[], responseText:string):void; @@ -206,8 +206,8 @@ declare class Dropzone { on(eventName:"uploadprogress", callback:(file:DropzoneFile, progress:number, bytesSent:number) => any):void; on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):void; - on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}) => any):void; - on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => any):void; + on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):void; + on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):void; on(eventName:"success", callback:(file:DropzoneFile) => any):void; on(eventName:"successmultiple", callback:(files:DropzoneFile[]) => any):void; @@ -246,8 +246,8 @@ declare class Dropzone { emit(eventName:"uploadprogress", file:DropzoneFile, progress:number, bytesSent:number):void; emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):void; - emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; emit(eventName:"success", file:DropzoneFile):void; emit(eventName:"successmultiple", files:DropzoneFile[]):void; From 6eaf28d3038a399f3724d831c86f4d525feace69 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Fri, 16 Sep 2016 14:32:42 +0300 Subject: [PATCH 103/154] Add justifyContent to CssProperties `justifyContent ` was missing from CssProperties and this PR adds it. More information about it [here](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content). --- react/react.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/react/react.d.ts b/react/react.d.ts index 5178ad28a6..30ab2db256 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1181,6 +1181,12 @@ declare namespace __React { imeMode?: any; + /** + * Defines how the browser distributes space between and around flex items + * along the main-axis of their container. + */ + justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; + layoutGrid?: any; layoutGridChar?: any; From 708b7be87332bd42d9d0db5db0398a95beae4e41 Mon Sep 17 00:00:00 2001 From: danderson00 Date: Mon, 19 Sep 2016 23:04:19 -0700 Subject: [PATCH 104/154] Fix hook function types --- azure-mobile-apps/azure-mobile-apps.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 4731d91eb2..54aaa66f8b 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -253,9 +253,9 @@ declare namespace Azure.MobileApps { softDelete?: boolean; userIdColumn?: string; - filters?: [(QueryJs, Context) => void | QueryJs]; - transforms?: [(any, Context) => void | any]; - hooks?: [(any, Context) => void]; + filters?: [(query: QueryJs, context: Context) => void | QueryJs]; + transforms?: [(item: any, context: Context) => void | any]; + hooks?: [(results: any, context: Context) => void]; perUser?: boolean; recordsExpire?: Duration; From 3dacedf0dc0f6c539dfb2751232d25a868752d54 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 11:33:29 +0300 Subject: [PATCH 105/154] Create index.d.ts --- react-redux-toastr/index.d.ts | 105 ++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 react-redux-toastr/index.d.ts diff --git a/react-redux-toastr/index.d.ts b/react-redux-toastr/index.d.ts new file mode 100644 index 0000000000..fb3dabfa61 --- /dev/null +++ b/react-redux-toastr/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for react-redux-toastr 3.7.0 +// Project: https://github.com/diegoddox/react-redux-toastr +// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "react-redux-toastr" { + import R = __React; + import _Redux = Redux; + + interface ToastrOptions { + /** + * Timeout in miliseconds. + */ + timeOut?: number, + /** + * Show newest on top or bottom. + */ + newestOnTop?: boolean, + /** + * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right + */ + position?: string, + confirmText?: ConfirmText + } + + interface ConfirmText { + okText: string, + cancelText: string + } + + /** + * Toastr react component. + */ + export default class ReduxToastr extends R.Component{ } + + interface EmitterOptions { + /** + * Notification popup icon. + * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert + */ + icon?: string, + /** + * Timeout in miliseconds. + */ + timeOut?: number, + removeOnHover?: boolean, + removeOnClick?: boolean, + component?: R.Component, + onShowComplete?: () => void, + onHideComplete?: () => void + } + + interface ToastrConfirmOptions { + onOk: () => void, + onCancel: () => void + } + + interface ToastrEmitter { + /** + * Used to provide a large amount of information. + * It will not close unless a timeOut is provided. + */ + message: (title: string, message: string, options?: EmitterOptions) => void, + info: (title: string, message: string, options?: EmitterOptions) => void, + success: (title: string, message: string, options?: EmitterOptions) => void, + warning: (title: string, message: string, options?: EmitterOptions) => void, + error: (title: string, message: string, options?: EmitterOptions) => void, + /** + * Clear all notifications + */ + clean: () => void, + /** + * Hook confirmation toastr with callback. + */ + confirm: (message: string, options: ToastrConfirmOptions) => any + } + + /** + * Possible actions to dispatch. + */ + interface Actions { + addToastrAction: Redux.Action, + clean: Redux.Action, + remove: Redux.Action, + success: Redux.Action, + info: Redux.Action, + warning: Redux.Action, + error: Redux.Action, + showConfirm: Redux.Action, + hideConfirm: Redux.Action + } + + /** + * Action creator for toastr. + */ + export var actions: Redux.ActionCreator; + /** + * Reducer for the toastr state. + * Combine with your reducers. + */ + export var reducer: Redux.Reducer; + /** + * Used to issue toastr notifications. + */ + export var toastr: ToastrEmitter; +} From 60b8d4769542d602022d0a7c521ac69ae7aff4ea Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 11:34:07 +0300 Subject: [PATCH 106/154] Create library-tests.ts --- react-redux-toastr/library-tests.ts | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 react-redux-toastr/library-tests.ts diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/library-tests.ts new file mode 100644 index 0000000000..427823b7c1 --- /dev/null +++ b/react-redux-toastr/library-tests.ts @@ -0,0 +1,51 @@ +/// +/// +/// +/// +import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; +import ReduxToastr from 'react-redux-toastr'; +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import {createStore, combineReducers, bindActionCreators} from 'redux'; +import { Provider, connect } from 'react-redux'; + +function test() { + const store = createStore(combineReducers({ toastr: toastrReducer })); + var toastrFactory = React.createFactory(ReduxToastr); + var element = toastrFactory({ timeOut: 1000, newestOnTop: false }); + var providerFactory = React.createFactory(Provider); + var root = providerFactory({ store: store }, element); + + class Test extends React.Component{ + private toastr; + constructor() { + super() + this.toastr = bindActionCreators(actions, this.props.dispatch); + this.toastr.clean(); + this.toastr.success("hi"); + } + + } + + + var TestComponent = connect(mapStateToProps, mapDispatchToProps)(Test); + function mapDispatchToProps(dispatch) { + return { + actions: bindActionCreators(actions, dispatch) + }; + } + + function mapStateToProps(state) { + return {}; + } + + function callback() { } + + toastr.clean(); + toastr.confirm("Test", { onOk: callback, onCancel: callback }); + toastr.error("Error", "Error message"); + toastr.info("Info", "Info test", { timeOut: 1000, removeOnHover: true, removeOnClick: true, onShowComplete: callback }); + toastr.success("Test", "Test message", { component: new React.Component() }); +} + +test(); From ab8d917787092fdfb16390f2bee6de8ab5c1783c Mon Sep 17 00:00:00 2001 From: Jay Anslow Date: Tue, 20 Sep 2016 09:55:32 +0100 Subject: [PATCH 107/154] Node.JS EventEmitter accepts symbols as event names. --- node/node-tests.ts | 4 ++-- node/node.d.ts | 46 +++++++++++++++++++++++----------------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 1fcf149e99..da3721c3aa 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -70,7 +70,7 @@ namespace assert_tests { namespace events_tests { let emitter: events.EventEmitter; - let event: string; + let event: string|symbol; let listener: Function; let any: any; @@ -114,7 +114,7 @@ namespace events_tests { } { - let result: string[]; + let result: (string|symbol)[]; result = emitter.eventNames(); } diff --git a/node/node.d.ts b/node/node.d.ts index 888da5cec4..7f228e1765 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -241,20 +241,20 @@ declare namespace NodeJS { } export class EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; + addListener(event: string|symbol, listener: Function): this; + on(event: string|symbol, listener: Function): this; + once(event: string|symbol, listener: Function): this; + removeListener(event: string|symbol, listener: Function): this; + removeAllListeners(event?: string|symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; + listeners(event: string|symbol): Function[]; + emit(event: string|symbol, ...args: any[]): boolean; + listenerCount(type: string|symbol): number; // Added in Node 6... - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - eventNames(): string[]; + prependListener(event: string|symbol, listener: Function): this; + prependOnceListener(event: string|symbol, listener: Function): this; + eventNames(): (string|symbol)[]; } export interface ReadableStream extends EventEmitter { @@ -549,22 +549,22 @@ declare module "querystring" { declare module "events" { export class EventEmitter extends NodeJS.EventEmitter { static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static listenerCount(emitter: EventEmitter, event: string|symbol): number; // deprecated static defaultMaxListeners: number; - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; + addListener(event: string|symbol, listener: Function): this; + on(event: string|symbol, listener: Function): this; + once(event: string|symbol, listener: Function): this; + prependListener(event: string|symbol, listener: Function): this; + prependOnceListener(event: string|symbol, listener: Function): this; + removeListener(event: string|symbol, listener: Function): this; + removeAllListeners(event?: string|symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - listenerCount(type: string): number; + listeners(event: string|symbol): Function[]; + emit(event: string|symbol, ...args: any[]): boolean; + eventNames(): (string|symbol)[]; + listenerCount(type: string|symbol): number; } } From a982c80d5537adbb10e61630436b6f33970c180c Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:45:34 +0300 Subject: [PATCH 108/154] Delete index.d.ts --- react-redux-toastr/index.d.ts | 105 ---------------------------------- 1 file changed, 105 deletions(-) delete mode 100644 react-redux-toastr/index.d.ts diff --git a/react-redux-toastr/index.d.ts b/react-redux-toastr/index.d.ts deleted file mode 100644 index fb3dabfa61..0000000000 --- a/react-redux-toastr/index.d.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Type definitions for react-redux-toastr 3.7.0 -// Project: https://github.com/diegoddox/react-redux-toastr -// Definitions by: Aleksandar Ivanov https://github.com/Smiche -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "react-redux-toastr" { - import R = __React; - import _Redux = Redux; - - interface ToastrOptions { - /** - * Timeout in miliseconds. - */ - timeOut?: number, - /** - * Show newest on top or bottom. - */ - newestOnTop?: boolean, - /** - * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right - */ - position?: string, - confirmText?: ConfirmText - } - - interface ConfirmText { - okText: string, - cancelText: string - } - - /** - * Toastr react component. - */ - export default class ReduxToastr extends R.Component{ } - - interface EmitterOptions { - /** - * Notification popup icon. - * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert - */ - icon?: string, - /** - * Timeout in miliseconds. - */ - timeOut?: number, - removeOnHover?: boolean, - removeOnClick?: boolean, - component?: R.Component, - onShowComplete?: () => void, - onHideComplete?: () => void - } - - interface ToastrConfirmOptions { - onOk: () => void, - onCancel: () => void - } - - interface ToastrEmitter { - /** - * Used to provide a large amount of information. - * It will not close unless a timeOut is provided. - */ - message: (title: string, message: string, options?: EmitterOptions) => void, - info: (title: string, message: string, options?: EmitterOptions) => void, - success: (title: string, message: string, options?: EmitterOptions) => void, - warning: (title: string, message: string, options?: EmitterOptions) => void, - error: (title: string, message: string, options?: EmitterOptions) => void, - /** - * Clear all notifications - */ - clean: () => void, - /** - * Hook confirmation toastr with callback. - */ - confirm: (message: string, options: ToastrConfirmOptions) => any - } - - /** - * Possible actions to dispatch. - */ - interface Actions { - addToastrAction: Redux.Action, - clean: Redux.Action, - remove: Redux.Action, - success: Redux.Action, - info: Redux.Action, - warning: Redux.Action, - error: Redux.Action, - showConfirm: Redux.Action, - hideConfirm: Redux.Action - } - - /** - * Action creator for toastr. - */ - export var actions: Redux.ActionCreator; - /** - * Reducer for the toastr state. - * Combine with your reducers. - */ - export var reducer: Redux.Reducer; - /** - * Used to issue toastr notifications. - */ - export var toastr: ToastrEmitter; -} From 02935de0ccd7821fcbea1e5b091f13b29d7df5f2 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:46:14 +0300 Subject: [PATCH 109/154] Update library-tests.ts --- react-redux-toastr/library-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/library-tests.ts index 427823b7c1..3abfc668d4 100644 --- a/react-redux-toastr/library-tests.ts +++ b/react-redux-toastr/library-tests.ts @@ -1,7 +1,7 @@ -/// -/// -/// -/// +/// +/// +/// +/// import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; import ReduxToastr from 'react-redux-toastr'; import * as React from 'react'; From 2837bdcd4b3e0ed0a326a6c28215709c345498a4 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:46:40 +0300 Subject: [PATCH 110/154] Rename library-tests.ts to react-redux-toastr-tests.ts --- .../{library-tests.ts => react-redux-toastr-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename react-redux-toastr/{library-tests.ts => react-redux-toastr-tests.ts} (100%) diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/react-redux-toastr-tests.ts similarity index 100% rename from react-redux-toastr/library-tests.ts rename to react-redux-toastr/react-redux-toastr-tests.ts From 18780a108d295a2a41ab690bc5747c33d9131931 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:47:05 +0300 Subject: [PATCH 111/154] Create react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 react-redux-toastr/react-redux-toastr.d.ts diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts new file mode 100644 index 0000000000..b10d430065 --- /dev/null +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -0,0 +1,108 @@ +// Type definitions for react-redux-toastr 3.7.0 +// Project: https://github.com/diegoddox/react-redux-toastr +// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +declare module "react-redux-toastr" { + import R = __React; + import _Redux = Redux; + + interface ToastrOptions { + /** + * Timeout in miliseconds. + */ + timeOut?: number, + /** + * Show newest on top or bottom. + */ + newestOnTop?: boolean, + /** + * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right + */ + position?: string, + confirmText?: ConfirmText + } + + interface ConfirmText { + okText: string, + cancelText: string + } + + /** + * Toastr react component. + */ + export default class ReduxToastr extends R.Component{ } + + interface EmitterOptions { + /** + * Notification popup icon. + * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert + */ + icon?: string, + /** + * Timeout in miliseconds. + */ + timeOut?: number, + removeOnHover?: boolean, + removeOnClick?: boolean, + component?: R.Component, + onShowComplete?: () => void, + onHideComplete?: () => void + } + + interface ToastrConfirmOptions { + onOk: () => void, + onCancel: () => void + } + + interface ToastrEmitter { + /** + * Used to provide a large amount of information. + * It will not close unless a timeOut is provided. + */ + message: (title: string, message: string, options?: EmitterOptions) => void, + info: (title: string, message: string, options?: EmitterOptions) => void, + success: (title: string, message: string, options?: EmitterOptions) => void, + warning: (title: string, message: string, options?: EmitterOptions) => void, + error: (title: string, message: string, options?: EmitterOptions) => void, + /** + * Clear all notifications + */ + clean: () => void, + /** + * Hook confirmation toastr with callback. + */ + confirm: (message: string, options: ToastrConfirmOptions) => any + } + + /** + * Possible actions to dispatch. + */ + interface Actions { + addToastrAction: Redux.Action, + clean: Redux.Action, + remove: Redux.Action, + success: Redux.Action, + info: Redux.Action, + warning: Redux.Action, + error: Redux.Action, + showConfirm: Redux.Action, + hideConfirm: Redux.Action + } + + /** + * Action creator for toastr. + */ + export var actions: Redux.ActionCreator; + /** + * Reducer for the toastr state. + * Combine with your reducers. + */ + export var reducer: Redux.Reducer; + /** + * Used to issue toastr notifications. + */ + export var toastr: ToastrEmitter; +} From e6e922c65ae7c97eee8adcb36acd1e9bcaae189d Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:55:37 +0300 Subject: [PATCH 112/154] Update react-redux-toastr-tests.ts --- .../react-redux-toastr-tests.ts | 25 +------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr-tests.ts b/react-redux-toastr/react-redux-toastr-tests.ts index 3abfc668d4..bd0426face 100644 --- a/react-redux-toastr/react-redux-toastr-tests.ts +++ b/react-redux-toastr/react-redux-toastr-tests.ts @@ -1,6 +1,6 @@ /// /// -/// +/// /// import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; import ReduxToastr from 'react-redux-toastr'; @@ -16,29 +16,6 @@ function test() { var providerFactory = React.createFactory(Provider); var root = providerFactory({ store: store }, element); - class Test extends React.Component{ - private toastr; - constructor() { - super() - this.toastr = bindActionCreators(actions, this.props.dispatch); - this.toastr.clean(); - this.toastr.success("hi"); - } - - } - - - var TestComponent = connect(mapStateToProps, mapDispatchToProps)(Test); - function mapDispatchToProps(dispatch) { - return { - actions: bindActionCreators(actions, dispatch) - }; - } - - function mapStateToProps(state) { - return {}; - } - function callback() { } toastr.clean(); From 42e0076772967425975dc40fcec076b7c06e1d9d Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:58:24 +0300 Subject: [PATCH 113/154] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index b10d430065..cef006ab20 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-redux-toastr 3.7.0 // Project: https://github.com/diegoddox/react-redux-toastr -// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions by: Aleksandar Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 0502f8480e068fafd516a1189f0ce25a26abb387 Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 20 Sep 2016 16:44:20 +0200 Subject: [PATCH 114/154] added import statement --- parse-mockdb/parse-mockdb-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/parse-mockdb/parse-mockdb-tests.ts b/parse-mockdb/parse-mockdb-tests.ts index 89f586d9e8..8d60573a8b 100644 --- a/parse-mockdb/parse-mockdb-tests.ts +++ b/parse-mockdb/parse-mockdb-tests.ts @@ -1,5 +1,7 @@ /// +import * as ParseMockDB from "parse-mockdb"; + ParseMockDB.mockDB(); // Mock the Parse RESTController // from parse-mockdb test suite From 962044d3ceb599d00c6ec69053218439b0df87cb Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 20 Sep 2016 10:46:08 -0400 Subject: [PATCH 115/154] Capitalize WebhookOptions --- twilio/twilio.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index c0f16211f5..824b596330 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -429,7 +429,7 @@ declare namespace twilio { export class TwimlResponse extends Node {} /// webhook.js - export interface webhookOptions { + export interface WebhookOptions { validate?: boolean; includeHelpers?: boolean; host?: string; @@ -450,8 +450,8 @@ declare namespace twilio { // For interop with node middleware chains export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } - export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; - export function webhook(options?: webhookOptions): MiddlewareFunction; + export function webhook(authToken: string, options?: WebhookOptions): MiddlewareFunction; + export function webhook(options?: WebhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; From be207d84a7df0bd0e3047fd60e447996ab707b04 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:03:49 +0300 Subject: [PATCH 116/154] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index cef006ab20..380dd3ad61 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -48,13 +48,13 @@ declare module "react-redux-toastr" { removeOnHover?: boolean, removeOnClick?: boolean, component?: R.Component, - onShowComplete?: () => void, - onHideComplete?: () => void + onShowComplete?: (): void; + onHideComplete?: (): void; } interface ToastrConfirmOptions { - onOk: () => void, - onCancel: () => void + onOk: (): void; + onCancel: (): void; } interface ToastrEmitter { @@ -62,19 +62,19 @@ declare module "react-redux-toastr" { * Used to provide a large amount of information. * It will not close unless a timeOut is provided. */ - message: (title: string, message: string, options?: EmitterOptions) => void, - info: (title: string, message: string, options?: EmitterOptions) => void, - success: (title: string, message: string, options?: EmitterOptions) => void, - warning: (title: string, message: string, options?: EmitterOptions) => void, - error: (title: string, message: string, options?: EmitterOptions) => void, + message: (title: string, message: string, options?: EmitterOptions): void; + info: (title: string, message: string, options?: EmitterOptions): void; + success: (title: string, message: string, options?: EmitterOptions): void; + warning: (title: string, message: string, options?: EmitterOptions): void; + error: (title: string, message: string, options?: EmitterOptions): void; /** * Clear all notifications */ - clean: () => void, + clean: (): void; /** * Hook confirmation toastr with callback. */ - confirm: (message: string, options: ToastrConfirmOptions) => any + confirm: (message: string, options: ToastrConfirmOptions): void; } /** From 913827f4c26e487db4454299e65f685f19ac6ced Mon Sep 17 00:00:00 2001 From: Aleksey Blokhin Date: Tue, 20 Sep 2016 18:14:10 +0300 Subject: [PATCH 117/154] `finally` returns original promise. --- js-data/js-data.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index 58bef671b1..284e66486b 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -15,7 +15,7 @@ declare namespace JSData { catch(onRejected?:(error:any) => U | JSDataPromise): JSDataPromise; // enhanced with finally - finally(finallyCb?:() => U):JSDataPromise; + finally(finallyCb?:() => any): JSDataPromise; } interface DSConfiguration extends IDSResourceLifecycleEventHandlers { From f11138f44326f40a9c676758ef2bf0164fa94a41 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:15:54 +0300 Subject: [PATCH 118/154] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index 380dd3ad61..21c72e093a 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -48,8 +48,8 @@ declare module "react-redux-toastr" { removeOnHover?: boolean, removeOnClick?: boolean, component?: R.Component, - onShowComplete?: (): void; - onHideComplete?: (): void; + onShowComplete?(): void; + onHideComplete?(): void; } interface ToastrConfirmOptions { @@ -62,19 +62,19 @@ declare module "react-redux-toastr" { * Used to provide a large amount of information. * It will not close unless a timeOut is provided. */ - message: (title: string, message: string, options?: EmitterOptions): void; - info: (title: string, message: string, options?: EmitterOptions): void; - success: (title: string, message: string, options?: EmitterOptions): void; - warning: (title: string, message: string, options?: EmitterOptions): void; - error: (title: string, message: string, options?: EmitterOptions): void; + message(title: string, message: string, options?: EmitterOptions): void; + info(title: string, message: string, options?: EmitterOptions): void; + success(title: string, message: string, options?: EmitterOptions): void; + warning(title: string, message: string, options?: EmitterOptions): void; + error(title: string, message: string, options?: EmitterOptions): void; /** * Clear all notifications */ - clean: (): void; + clean(): void; /** * Hook confirmation toastr with callback. */ - confirm: (message: string, options: ToastrConfirmOptions): void; + confirm(message: string, options: ToastrConfirmOptions): void; } /** From 41e5e3d1782f6ded0a0bfdc22f2032550c966ca3 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:16:27 +0300 Subject: [PATCH 119/154] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index 21c72e093a..1b628455aa 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -53,8 +53,8 @@ declare module "react-redux-toastr" { } interface ToastrConfirmOptions { - onOk: (): void; - onCancel: (): void; + onOk(): void; + onCancel(): void; } interface ToastrEmitter { From 19425cf32716e63bbbce6a091ec83eaf81a1a3ca Mon Sep 17 00:00:00 2001 From: "Boland, Craig" Date: Tue, 20 Sep 2016 12:22:11 -0500 Subject: [PATCH 120/154] Updated jquery.dataTables.d.ts for 1.10.6. Version release notes: https://cdn.datatables.net/1.10.6/ * Added rows().every() * Added columns().every() * Added cells().every() * Added init() * Expanded method signature when ajax.data is used as a function. --- jquery.dataTables/jquery.dataTables-tests.ts | 196 ++++++++++--------- jquery.dataTables/jquery.dataTables.d.ts | 58 ++++-- 2 files changed, 147 insertions(+), 107 deletions(-) diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index 4d1d114cb4..6329861604 100644 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -82,21 +82,21 @@ $(document).ready(function () { width: "200px" } col = - { - data: "", - orderData: [10, 11, 20], - render: "", - } + { + data: "", + orderData: [10, 11, 20], + render: "", + } col = - { - data: colDataObject, - render: colRenderObject, - } + { + data: colDataObject, + render: colRenderObject, + } col = - { - data: colDataFunc, - render: colRenderFunc, - } + { + data: colDataFunc, + render: colRenderFunc, + } //#endregion "Column" @@ -124,16 +124,16 @@ $(document).ready(function () { }; colDef = - { - targets: "2", - cellType: "th", - }; + { + targets: "2", + cellType: "th", + }; colDef = - { - targets: ["2", 5], - cellType: "th", - }; + { + targets: ["2", 5], + cellType: "th", + }; //#endregion "ColumnDef" @@ -159,7 +159,7 @@ $(document).ready(function () { var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { }; - var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) { + var ajaxDataFunc: DataTables.FunctionAjaxData = function (data, settings) { return data; }; @@ -229,41 +229,41 @@ $(document).ready(function () { config = - { - ajax: ajaxFunc, - deferLoading: [10, 100], - lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], - order: [0, 'asc'], - orderFixed: [[0, 'asc'], [1, 'asc']], - renderer: { - header: "bootstrap", - pageButton: "jqueryui" - }, - search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - searchCols: [ - null, - { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - { "search": "" }, - { "search": "", "smart": true }, - null - ], - }; + { + ajax: ajaxFunc, + deferLoading: [10, 100], + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + order: [0, 'asc'], + orderFixed: [[0, 'asc'], [1, 'asc']], + renderer: { + header: "bootstrap", + pageButton: "jqueryui" + }, + search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + searchCols: [ + null, + { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + { "search": "" }, + { "search": "", "smart": true }, + null + ], + }; config = - { - ajax: { - data: {}, - dataSrc: "", - }, - }; + { + ajax: { + data: {}, + dataSrc: "", + }, + }; config = - { - ajax: { - data: ajaxDataFunc, - dataSrc: function (data) { }, - }, - }; + { + ajax: { + data: ajaxDataFunc, + dataSrc: function (data) { }, + }, + }; //#endregion "Settings" @@ -309,6 +309,8 @@ $(document).ready(function () { draw = dt.draw(true); draw.$(""); + var initSettings = dt.init(); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -385,11 +387,11 @@ $(document).ready(function () { var select = $('