From 71022e82f1ed8cf717d60b5fda1f2c241c186004 Mon Sep 17 00:00:00 2001 From: Peter Wilczynski Date: Wed, 24 Feb 2016 09:07:09 -0800 Subject: [PATCH 01/53] Fix typings for Leaflet.LineUtils.clipSegement() --- leaflet/leaflet.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index fd696b2a5..089c16db7 100755 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -2000,11 +2000,11 @@ declare namespace L { export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; /** - * Clips the segment a to b by rectangular bounds (modifying the segment points - * directly!). Used by Leaflet to only show polyline points that are on the screen - * or near, increasing performance. + * 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): void; + export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; } } From 21f0aaa603d3dfdfe0353a9a069228d427026321 Mon Sep 17 00:00:00 2001 From: Giedrius Grabauskas Date: Thu, 17 Mar 2016 19:16:24 +0200 Subject: [PATCH 02/53] Created and implemented error interface --- signalr/signalr.d.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/signalr/signalr.d.ts b/signalr/signalr.d.ts index 73b6fdef8..9b0131f6c 100644 --- a/signalr/signalr.d.ts +++ b/signalr/signalr.d.ts @@ -24,7 +24,7 @@ declare namespace SignalR { name: string; supportsKeepAlive(): boolean; send(connection: SignalR.Connection, data: any): void; - start(connection: SignalR.Connection, onSuccess: () => void, onFailed: (error?: any) => void): void; + start(connection: SignalR.Connection, onSuccess: () => void, onFailed: (error?: ConnectionError) => void): void; reconnect(connection: SignalR.Connection): void; lostConnection(connection: SignalR.Connection): void; stop(connection: SignalR.Connection): void; @@ -169,6 +169,18 @@ declare namespace SignalR { protocol: string; host: string; } + + interface ConnectionErrorContext { + readyState: number; + responseText: string; + status: number; + statusText: string; + } + + interface ConnectionError extends Error { + context: ConnectionErrorContext; + transport?: string; + } interface Connection { clientProtocol: string; @@ -256,7 +268,7 @@ declare namespace SignalR { * * @param calback A callback function to execute when an error occurs on the connection */ - error(callback: (error: Error) => void): Connection; + error(callback: (error: ConnectionError) => void): Connection; /** * Adds a callback that will be invoked when the client disconnects @@ -306,7 +318,7 @@ declare namespace SignalR { hub: Hub.Connection; - lastError: any; + lastError: ConnectionError; resources: Resources; } } From 123af07d7e28d930d16494981c8c9d812989b28c Mon Sep 17 00:00:00 2001 From: Florent Poujol Date: Mon, 29 Feb 2016 17:57:28 +0100 Subject: [PATCH 03/53] Update definitions to THREE.js r74 --- threejs/tests/math/test_unit_math.ts | 137 +- .../webgl/webgl_animation_skinning_morph.ts | 2 - ...imsphere.ts => webgl_lights_hemisphere.ts} | 1 - threejs/tests/webgl/webgl_materials.ts | 2 +- threejs/three-tests.ts | 2 +- threejs/three.d.ts | 2469 +++++++++-------- 6 files changed, 1454 insertions(+), 1159 deletions(-) rename threejs/tests/webgl/{webgl_lights_heimsphere.ts => webgl_lights_hemisphere.ts} (98%) diff --git a/threejs/tests/math/test_unit_math.ts b/threejs/tests/math/test_unit_math.ts index 0c92e970a..5d095315d 100644 --- a/threejs/tests/math/test_unit_math.ts +++ b/threejs/tests/math/test_unit_math.ts @@ -212,23 +212,23 @@ ok( b.distanceToPoint( new THREE.Vector2( -2, -2 ) ) == Math.sqrt( 2 ), "Passed!" ); }); - test( "isIntersectionBox", function() { + test( "intersectsBox", function() { var a = new THREE.Box2( zero2.clone(), zero2.clone() ); var b = new THREE.Box2( zero2.clone(), one2.clone() ); var c = new THREE.Box2( one2.clone().negate(), one2.clone() ); - ok( a.isIntersectionBox( a ), "Passed!" ); - ok( a.isIntersectionBox( b ), "Passed!" ); - ok( a.isIntersectionBox( c ), "Passed!" ); + ok( a.intersectsBox( a ), "Passed!" ); + ok( a.intersectsBox( b ), "Passed!" ); + ok( a.intersectsBox( c ), "Passed!" ); - ok( b.isIntersectionBox( a ), "Passed!" ); - ok( c.isIntersectionBox( a ), "Passed!" ); - ok( b.isIntersectionBox( c ), "Passed!" ); + ok( b.intersectsBox( a ), "Passed!" ); + ok( c.intersectsBox( a ), "Passed!" ); + ok( b.intersectsBox( c ), "Passed!" ); b.translate( new THREE.Vector2( 2, 2 ) ); - ok( ! a.isIntersectionBox( b ), "Passed!" ); - ok( ! b.isIntersectionBox( a ), "Passed!" ); - ok( ! b.isIntersectionBox( c ), "Passed!" ); + ok( ! a.intersectsBox( b ), "Passed!" ); + ok( ! b.intersectsBox( a ), "Passed!" ); + ok( ! b.intersectsBox( c ), "Passed!" ); }); test( "intersect", function() { @@ -468,23 +468,23 @@ ok( b.distanceToPoint( new THREE.Vector3( -2, -2, -2 ) ) == Math.sqrt( 3 ), "Passed!" ); }); - test( "isIntersectionBox", function() { + test( "intersectsBox", function() { var a = new THREE.Box3( zero3.clone(), zero3.clone() ); var b = new THREE.Box3( zero3.clone(), one3.clone() ); var c = new THREE.Box3( one3.clone().negate(), one3.clone() ); - ok( a.isIntersectionBox( a ), "Passed!" ); - ok( a.isIntersectionBox( b ), "Passed!" ); - ok( a.isIntersectionBox( c ), "Passed!" ); + ok( a.intersectsBox( a ), "Passed!" ); + ok( a.intersectsBox( b ), "Passed!" ); + ok( a.intersectsBox( c ), "Passed!" ); - ok( b.isIntersectionBox( a ), "Passed!" ); - ok( c.isIntersectionBox( a ), "Passed!" ); - ok( b.isIntersectionBox( c ), "Passed!" ); + ok( b.intersectsBox( a ), "Passed!" ); + ok( c.intersectsBox( a ), "Passed!" ); + ok( b.intersectsBox( c ), "Passed!" ); b.translate( new THREE.Vector3( 2, 2, 2 ) ); - ok( ! a.isIntersectionBox( b ), "Passed!" ); - ok( ! b.isIntersectionBox( a ), "Passed!" ); - ok( ! b.isIntersectionBox( c ), "Passed!" ); + ok( ! a.intersectsBox( b ), "Passed!" ); + ok( ! b.intersectsBox( a ), "Passed!" ); + ok( ! b.intersectsBox( c ), "Passed!" ); }); test( "getBoundingSphere", function() { @@ -1149,7 +1149,8 @@ var a = new THREE.Matrix3(); ok( a.determinant() == 1, "Passed!" ); - var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var b = new THREE.Matrix3(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8); ok( b.elements[0] == 0 ); ok( b.elements[1] == 3 ); ok( b.elements[2] == 6 ); @@ -1164,7 +1165,8 @@ }); test( "copy", function() { - var a = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var a = new THREE.Matrix3(); + a.set(0, 1, 2, 3, 4, 5, 6, 7, 8); var b = new THREE.Matrix3().copy( a ); ok( matrixEquals3( a, b ), "Passed!" ); @@ -1191,7 +1193,8 @@ }); test( "identity", function() { - var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var b = new THREE.Matrix3(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8); ok( b.elements[0] == 0 ); ok( b.elements[1] == 3 ); ok( b.elements[2] == 6 ); @@ -1210,7 +1213,8 @@ }); test( "multiplyScalar", function() { - var b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var b = new THREE.Matrix3(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8); ok( b.elements[0] == 0 ); ok( b.elements[1] == 3 ); ok( b.elements[2] == 6 ); @@ -1252,8 +1256,10 @@ test( "getInverse", function() { var identity = new THREE.Matrix4(); var a = new THREE.Matrix4(); - var b = new THREE.Matrix3( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + var b = new THREE.Matrix3(); + b.set(0, 0, 0, 0, 0, 0, 0, 0, 0); + var c = new THREE.Matrix4(); + c.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); ok( ! matrixEquals3( a, b ), "Passed!" ); b.getInverse( a, false ); @@ -1299,7 +1305,8 @@ var b = a.clone().transpose(); ok( matrixEquals3( a, b ), "Passed!" ); - b = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + b = new THREE.Matrix3(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8); var c = b.clone().transpose(); ok( ! matrixEquals3( b, c ), "Passed!" ); c.transpose(); @@ -1307,7 +1314,8 @@ }); test( "clone", function() { - var a = new THREE.Matrix3( 0, 1, 2, 3, 4, 5, 6, 7, 8 ); + var a = new THREE.Matrix3(); + a.set(0, 1, 2, 3, 4, 5, 6, 7, 8); var b = a.clone(); ok( matrixEquals3( a, b ), "Passed!" ); @@ -1337,7 +1345,8 @@ var a = new THREE.Matrix4(); ok( a.determinant() == 1, "Passed!" ); - var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var b = new THREE.Matrix4(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ok( b.elements[0] == 0 ); ok( b.elements[1] == 4 ); ok( b.elements[2] == 8 ); @@ -1359,7 +1368,8 @@ }); test( "copy", function() { - var a = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var a = new THREE.Matrix4(); + a.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); var b = new THREE.Matrix4().copy( a ); ok( matrixEquals4( a, b ), "Passed!" ); @@ -1393,7 +1403,8 @@ }); test( "identity", function() { - var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var b = new THREE.Matrix4(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ok( b.elements[0] == 0 ); ok( b.elements[1] == 4 ); ok( b.elements[2] == 8 ); @@ -1419,7 +1430,8 @@ }); test( "multiplyScalar", function() { - var b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var b = new THREE.Matrix4(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); ok( b.elements[0] == 0 ); ok( b.elements[1] == 4 ); ok( b.elements[2] == 8 ); @@ -1475,8 +1487,8 @@ var identity = new THREE.Matrix4(); var a = new THREE.Matrix4(); - var b = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); - var c = new THREE.Matrix4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); + var b = new THREE.Matrix4().set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + var c = new THREE.Matrix4().set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); ok( ! matrixEquals4( a, b ), "Passed!" ); b.getInverse( a, false ); @@ -1561,7 +1573,8 @@ var b = a.clone().transpose(); ok( matrixEquals4( a, b ), "Passed!" ); - b = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + b = new THREE.Matrix4(); + b.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); var c = b.clone().transpose(); ok( ! matrixEquals4( b, c ), "Passed!" ); c.transpose(); @@ -1569,7 +1582,8 @@ }); test( "clone", function() { - var a = new THREE.Matrix4( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ); + var a = new THREE.Matrix4(); + a.set(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); var b = a.clone(); ok( matrixEquals4( a, b ), "Passed!" ); @@ -1773,23 +1787,23 @@ var a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 0 ); var l1 = new THREE.Line3( new THREE.Vector3( -10, 0, 0 ), new THREE.Vector3( 10, 0, 0 ) ); - ok( a.isIntersectionLine( l1 ), "Passed!" ); + ok( a.intersectsLine( l1 ), "Passed!" ); ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 0, 0, 0 ) ), "Passed!" ); a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -3 ); - ok( a.isIntersectionLine( l1 ), "Passed!" ); + ok( a.intersectsLine( l1 ), "Passed!" ); ok( a.intersectLine( l1 ).equals( new THREE.Vector3( 3, 0, 0 ) ), "Passed!" ); a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), -11 ); - ok( ! a.isIntersectionLine( l1 ), "Passed!" ); + ok( ! a.intersectsLine( l1 ), "Passed!" ); ok( a.intersectLine( l1 ) === undefined, "Passed!" ); a = new THREE.Plane( new THREE.Vector3( 1, 0, 0 ), 11 ); - ok( ! a.isIntersectionLine( l1 ), "Passed!" ); + ok( ! a.intersectsLine( l1 ), "Passed!" ); ok( a.intersectLine( l1 ) === undefined, "Passed!" ); }); @@ -2136,7 +2150,7 @@ ok( d === 0, "Passed!" ); }); - test( "isIntersectionSphere", function() { + test( "intersectsSphere", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); var b = new THREE.Sphere( zero3, 0.5 ); var c = new THREE.Sphere( zero3, 1.5 ); @@ -2144,11 +2158,11 @@ var e = new THREE.Sphere( two3, 0.1 ); var f = new THREE.Sphere( two3, 1 ); - ok( ! a.isIntersectionSphere( b ), "Passed!" ); - ok( ! a.isIntersectionSphere( c ), "Passed!" ); - ok( a.isIntersectionSphere( d ), "Passed!" ); - ok( ! a.isIntersectionSphere( e ), "Passed!" ); - ok( ! a.isIntersectionSphere( f ), "Passed!" ); + ok( ! a.intersectsSphere( b ), "Passed!" ); + ok( ! a.intersectsSphere( c ), "Passed!" ); + ok( a.intersectsSphere( d ), "Passed!" ); + ok( ! a.intersectsSphere( e ), "Passed!" ); + ok( ! a.intersectsSphere( f ), "Passed!" ); }); test( "intersectSphere", function() { @@ -2210,28 +2224,28 @@ }); - test( "isIntersectionPlane", function() { + test( "intersectsPlane", function() { var a = new THREE.Ray( one3.clone(), new THREE.Vector3( 0, 0, 1 ) ); // parallel plane in front of the ray var b = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, -1 ) ) ); - ok( a.isIntersectionPlane( b ), "Passed!" ); + ok( a.intersectsPlane( b ), "Passed!" ); // parallel plane coincident with origin var c = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 0 ) ) ); - ok( a.isIntersectionPlane( c ), "Passed!" ); + ok( a.intersectsPlane( c ), "Passed!" ); // parallel plane behind the ray var d = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 0, 0, 1 ), one3.clone().sub( new THREE.Vector3( 0, 0, 1 ) ) ); - ok( ! a.isIntersectionPlane( d ), "Passed!" ); + ok( ! a.intersectsPlane( d ), "Passed!" ); // perpendical ray that overlaps exactly var e = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), one3 ); - ok( a.isIntersectionPlane( e ), "Passed!" ); + ok( a.intersectsPlane( e ), "Passed!" ); // perpendical ray that doesn't overlap var f = new THREE.Plane().setFromNormalAndCoplanarPoint( new THREE.Vector3( 1, 0, 0 ), zero3 ); - ok( ! a.isIntersectionPlane( f ), "Passed!" ); + ok( ! a.intersectsPlane( f ), "Passed!" ); }); test( "intersectPlane", function() { @@ -2327,32 +2341,32 @@ var a = new THREE.Ray( new THREE.Vector3( -2, 0, 0 ), new THREE.Vector3( 1, 0, 0) ); //ray should intersect box at -1,0,0 - ok( a.isIntersectionBox(box) === true, "Passed!" ); + ok( a.intersectsBox(box) === true, "Passed!" ); ok( a.intersectBox(box).distanceTo( new THREE.Vector3( -1, 0, 0 ) ) < TOL, "Passed!" ); var b = new THREE.Ray( new THREE.Vector3( -2, 0, 0 ), new THREE.Vector3( -1, 0, 0) ); //ray is point away from box, it should not intersect - ok( b.isIntersectionBox(box) === false, "Passed!" ); + ok( b.intersectsBox(box) === false, "Passed!" ); ok( b.intersectBox(box) === null, "Passed!" ); var c = new THREE.Ray( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 1, 0, 0) ); // ray is inside box, should return exit point - ok( c.isIntersectionBox(box) === true, "Passed!" ); + ok( c.intersectsBox(box) === true, "Passed!" ); ok( c.intersectBox(box).distanceTo( new THREE.Vector3( 1, 0, 0 ) ) < TOL, "Passed!" ); var d = new THREE.Ray( new THREE.Vector3( 0, 2, 1 ), new THREE.Vector3( 0, -1, -1).normalize() ); //tilted ray should intersect box at 0,1,0 - ok( d.isIntersectionBox(box) === true, "Passed!" ); + ok( d.intersectsBox(box) === true, "Passed!" ); ok( d.intersectBox(box).distanceTo( new THREE.Vector3( 0, 1, 0 ) ) < TOL, "Passed!" ); var e = new THREE.Ray( new THREE.Vector3( 1, -2, 1 ), new THREE.Vector3( 0, 1, 0).normalize() ); //handle case where ray is coplanar with one of the boxes side - box in front of ray - ok( e.isIntersectionBox(box) === true, "Passed!" ); + ok( e.intersectsBox(box) === true, "Passed!" ); ok( e.intersectBox(box).distanceTo( new THREE.Vector3( 1, -1, 1 ) ) < TOL, "Passed!" ); var f = new THREE.Ray( new THREE.Vector3( 1, -2, 0 ), new THREE.Vector3( 0, -1, 0).normalize() ); //handle case where ray is coplanar with one of the boxes side - box behind ray - ok( f.isIntersectionBox(box) === false, "Passed!" ); + ok( f.intersectsBox(box) === false, "Passed!" ); ok( f.intersectBox(box) == null, "Passed!" ); }); @@ -3527,13 +3541,14 @@ test( "setAxisAngleFromRotationMatrix", function() { var TOL = 1e-9; - - var r = new THREE.Matrix4().makeRotationZ(Math.PI / 2); + + // not sure what to do here since THREE.Vector4().setAxisAngleFromRotationMatrix() only accept Matrix3s + /*var r = new THREE.Matrix4().makeRotationZ(Math.PI / 2); var v = new THREE.Vector4().setAxisAngleFromRotationMatrix(r); ok( v.x == 0, "Passed!" ); ok( v.y == 0, "Passed!" ); ok( v.z == 1, "Passed!" ); - ok( Math.abs(v.w - Math.PI / 2) < TOL, "Passed!" ); + ok( Math.abs(v.w - Math.PI / 2) < TOL, "Passed!" );*/ }); }; diff --git a/threejs/tests/webgl/webgl_animation_skinning_morph.ts b/threejs/tests/webgl/webgl_animation_skinning_morph.ts index 7c65905ae..50976c454 100644 --- a/threejs/tests/webgl/webgl_animation_skinning_morph.ts +++ b/threejs/tests/webgl/webgl_animation_skinning_morph.ts @@ -186,8 +186,6 @@ var clipBones = geometry.animations[0]; mixer = new THREE.AnimationMixer( mesh ); - mixer.addAction( new THREE.AnimationAction( clipMorpher ) ); - mixer.addAction( new THREE.AnimationAction( clipBones ) ); } function initGUI() { diff --git a/threejs/tests/webgl/webgl_lights_heimsphere.ts b/threejs/tests/webgl/webgl_lights_hemisphere.ts similarity index 98% rename from threejs/tests/webgl/webgl_lights_heimsphere.ts rename to threejs/tests/webgl/webgl_lights_hemisphere.ts index fd2118e62..892b3ed4c 100644 --- a/threejs/tests/webgl/webgl_lights_heimsphere.ts +++ b/threejs/tests/webgl/webgl_lights_hemisphere.ts @@ -130,7 +130,6 @@ scene.add( mesh ); var mixer = new THREE.AnimationMixer( mesh ); - mixer.addAction( new THREE.AnimationAction( geometry.animations[ 0 ] ).warpToDuration( 1 ) ); mixers.push( mixer ); } ); diff --git a/threejs/tests/webgl/webgl_materials.ts b/threejs/tests/webgl/webgl_materials.ts index a78ae152a..5426a1fb2 100644 --- a/threejs/tests/webgl/webgl_materials.ts +++ b/threejs/tests/webgl/webgl_materials.ts @@ -62,7 +62,7 @@ materials.push(new THREE.MeshLambertMaterial({ color: 0xdddddd })); materials.push(new THREE.MeshPhongMaterial({ color: 0xdddddd, specular: 0x009900, shininess: 30, shading: THREE.SmoothShading, map: texture, transparent: true })); - materials.push(new THREE.MeshNormalMaterial({ shading: THREE.SmoothShading })); + materials.push(new THREE.MeshNormalMaterial({})); materials.push(new THREE.MeshBasicMaterial({ color: 0xffaa00, wireframe: true })); materials.push(new THREE.MeshDepthMaterial()); diff --git a/threejs/three-tests.ts b/threejs/three-tests.ts index 2e9f37b10..282f699d2 100644 --- a/threejs/three-tests.ts +++ b/threejs/three-tests.ts @@ -35,7 +35,7 @@ THE SOFTWARE. /// /// /// -/// +/// /// /// /// diff --git a/threejs/three.d.ts b/threejs/three.d.ts index a65a52afd..14d2c0b4e 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -1,174 +1,194 @@ -// Type definitions for three.js r73 +// Type definitions for three.js r74 // Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon , Satoru Kimura -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions by: Kon , Satoru Kimura , Florent Poujol +// Definitions: https://github.com/borisyankov/DefinitelyTyped declare namespace THREE { - export var REVISION: string; + export const REVISION: string; // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button export enum MOUSE { LEFT, MIDDLE, RIGHT } // GL STATE CONSTANTS export enum CullFace { } - export var CullFaceNone: CullFace; - export var CullFaceBack: CullFace; - export var CullFaceFront: CullFace; - export var CullFaceFrontBack: CullFace; + export const CullFaceNone: CullFace; + export const CullFaceBack: CullFace; + export const CullFaceFront: CullFace; + export const CullFaceFrontBack: CullFace; export enum FrontFaceDirection { } - export var FrontFaceDirectionCW: FrontFaceDirection; - export var FrontFaceDirectionCCW: FrontFaceDirection; + export const FrontFaceDirectionCW: FrontFaceDirection; + export const FrontFaceDirectionCCW: FrontFaceDirection; // Shadowing Type export enum ShadowMapType { } - export var BasicShadowMap: ShadowMapType; - export var PCFShadowMap: ShadowMapType; - export var PCFSoftShadowMap: ShadowMapType; + export const BasicShadowMap: ShadowMapType; + export const PCFShadowMap: ShadowMapType; + export const PCFSoftShadowMap: ShadowMapType; // MATERIAL CONSTANTS // side export enum Side { } - export var FrontSide: Side; - export var BackSide: Side; - export var DoubleSide: Side; + export const FrontSide: Side; + export const BackSide: Side; + export const DoubleSide: Side; // shading export enum Shading { } - export var NoShading: Shading; - export var FlatShading: Shading; - export var SmoothShading: Shading; + export const FlatShading: Shading; + export const SmoothShading: Shading; // colors export enum Colors { } - export var NoColors: Colors; - export var FaceColors: Colors; - export var VertexColors: Colors; + export const NoColors: Colors; + export const FaceColors: Colors; + export const VertexColors: Colors; // blending modes export enum Blending { } - export var NoBlending: Blending; - export var NormalBlending: Blending; - export var AdditiveBlending: Blending; - export var SubtractiveBlending: Blending; - export var MultiplyBlending: Blending; - export var CustomBlending: Blending; + export const NoBlending: Blending; + export const NormalBlending: Blending; + export const AdditiveBlending: Blending; + export const SubtractiveBlending: Blending; + export const MultiplyBlending: Blending; + export const CustomBlending: Blending; // custom blending equations // (numbers start from 100 not to clash with other // mappings to OpenGL constants defined in Texture.js) export enum BlendingEquation { } - export var AddEquation: BlendingEquation; - export var SubtractEquation: BlendingEquation; - export var ReverseSubtractEquation: BlendingEquation; - export var MinEquation: BlendingEquation; - export var MaxEquation: BlendingEquation; + export const AddEquation: BlendingEquation; + export const SubtractEquation: BlendingEquation; + export const ReverseSubtractEquation: BlendingEquation; + export const MinEquation: BlendingEquation; + export const MaxEquation: BlendingEquation; // custom blending destination factors export enum BlendingDstFactor { } - export var ZeroFactor: BlendingDstFactor; - export var OneFactor: BlendingDstFactor; - export var SrcColorFactor: BlendingDstFactor; - export var OneMinusSrcColorFactor: BlendingDstFactor; - export var SrcAlphaFactor: BlendingDstFactor; - export var OneMinusSrcAlphaFactor: BlendingDstFactor; - export var DstAlphaFactor: BlendingDstFactor; - export var OneMinusDstAlphaFactor: BlendingDstFactor; + export const ZeroFactor: BlendingDstFactor; + export const OneFactor: BlendingDstFactor; + export const SrcColorFactor: BlendingDstFactor; + export const OneMinusSrcColorFactor: BlendingDstFactor; + export const SrcAlphaFactor: BlendingDstFactor; + export const OneMinusSrcAlphaFactor: BlendingDstFactor; + export const DstAlphaFactor: BlendingDstFactor; + export const OneMinusDstAlphaFactor: BlendingDstFactor; // custom blending src factors export enum BlendingSrcFactor { } - export var DstColorFactor: BlendingSrcFactor; - export var OneMinusDstColorFactor: BlendingSrcFactor; - export var SrcAlphaSaturateFactor: BlendingSrcFactor; + export const DstColorFactor: BlendingSrcFactor; + export const OneMinusDstColorFactor: BlendingSrcFactor; + export const SrcAlphaSaturateFactor: BlendingSrcFactor; // depth modes export enum DepthModes { } - export var NeverDepth: DepthModes; - export var AlwaysDepth: DepthModes; - export var LessDepth: DepthModes; - export var LessEqualDepth: DepthModes; - export var EqualDepth: DepthModes; - export var GreaterEqualDepth: DepthModes; - export var GreaterDepth: DepthModes; - export var NotEqualDepth: DepthModes; + export const NeverDepth: DepthModes; + export const AlwaysDepth: DepthModes; + export const LessDepth: DepthModes; + export const LessEqualDepth: DepthModes; + export const EqualDepth: DepthModes; + export const GreaterEqualDepth: DepthModes; + export const GreaterDepth: DepthModes; + export const NotEqualDepth: DepthModes; // TEXTURE CONSTANTS // Operations export enum Combine { } - export var MultiplyOperation: Combine; - export var MixOperation: Combine; - export var AddOperation: Combine; + export const MultiplyOperation: Combine; + export const MixOperation: Combine; + export const AddOperation: Combine; // Mapping modes export enum Mapping { } - export var UVMapping: Mapping; - export var CubeReflectionMapping: Mapping; - export var CubeRefractionMapping: Mapping; - export var EquirectangularReflectionMapping: Mapping; - export var EquirectangularRefractionMapping: Mapping; - export var SphericalReflectionMapping: Mapping; + export const UVMapping: Mapping; + export const CubeReflectionMapping: Mapping; + export const CubeRefractionMapping: Mapping; + export const EquirectangularReflectionMapping: Mapping; + export const EquirectangularRefractionMapping: Mapping; + export const SphericalReflectionMapping: Mapping; // Wrapping modes export enum Wrapping { } - export var RepeatWrapping: Wrapping; - export var ClampToEdgeWrapping: Wrapping; - export var MirroredRepeatWrapping: Wrapping; + export const RepeatWrapping: Wrapping; + export const ClampToEdgeWrapping: Wrapping; + export const MirroredRepeatWrapping: Wrapping; // Filters export enum TextureFilter { } - export var NearestFilter: TextureFilter; - export var NearestMipMapNearestFilter: TextureFilter; - export var NearestMipMapLinearFilter: TextureFilter; - export var LinearFilter: TextureFilter; - export var LinearMipMapNearestFilter: TextureFilter; - export var LinearMipMapLinearFilter: TextureFilter; + export const NearestFilter: TextureFilter; + export const NearestMipMapNearestFilter: TextureFilter; + export const NearestMipMapLinearFilter: TextureFilter; + export const LinearFilter: TextureFilter; + export const LinearMipMapNearestFilter: TextureFilter; + export const LinearMipMapLinearFilter: TextureFilter; // Data types export enum TextureDataType { } - export var UnsignedByteType: TextureDataType; - export var ByteType: TextureDataType; - export var ShortType: TextureDataType; - export var UnsignedShortType: TextureDataType; - export var IntType: TextureDataType; - export var UnsignedIntType: TextureDataType; - export var FloatType: TextureDataType; - export var HalfFloatType: TextureDataType; + export const UnsignedByteType: TextureDataType; + export const ByteType: TextureDataType; + export const ShortType: TextureDataType; + export const UnsignedShortType: TextureDataType; + export const IntType: TextureDataType; + export const UnsignedIntType: TextureDataType; + export const FloatType: TextureDataType; + export const HalfFloatType: TextureDataType; // Pixel types export enum PixelType { } - export var UnsignedShort4444Type: PixelType; - export var UnsignedShort5551Type: PixelType; - export var UnsignedShort565Type: PixelType; + export const UnsignedShort4444Type: PixelType; + export const UnsignedShort5551Type: PixelType; + export const UnsignedShort565Type: PixelType; // Pixel formats export enum PixelFormat { } - export var AlphaFormat: PixelFormat; - export var RGBFormat: PixelFormat; - export var RGBAFormat: PixelFormat; - export var LuminanceFormat: PixelFormat; - export var LuminanceAlphaFormat: PixelFormat; - export var RGBEFormat: PixelFormat; + export const AlphaFormat: PixelFormat; + export const RGBFormat: PixelFormat; + export const RGBAFormat: PixelFormat; + export const LuminanceFormat: PixelFormat; + export const LuminanceAlphaFormat: PixelFormat; + export const RGBEFormat: PixelFormat; // Compressed texture formats // DDS / ST3C Compressed texture formats export enum CompressedPixelFormat { } - export var RGB_S3TC_DXT1_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT1_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT3_Format: CompressedPixelFormat; - export var RGBA_S3TC_DXT5_Format: CompressedPixelFormat; + export const RGB_S3TC_DXT1_Format: CompressedPixelFormat; + export const RGBA_S3TC_DXT1_Format: CompressedPixelFormat; + export const RGBA_S3TC_DXT3_Format: CompressedPixelFormat; + export const RGBA_S3TC_DXT5_Format: CompressedPixelFormat; // PVRTC compressed texture formats - export var RGB_PVRTC_4BPPV1_Format: CompressedPixelFormat; - export var RGB_PVRTC_2BPPV1_Format: CompressedPixelFormat; - export var RGBA_PVRTC_4BPPV1_Format: CompressedPixelFormat; - export var RGBA_PVRTC_2BPPV1_Format: CompressedPixelFormat; + export const RGB_PVRTC_4BPPV1_Format: CompressedPixelFormat; + export const RGB_PVRTC_2BPPV1_Format: CompressedPixelFormat; + export const RGBA_PVRTC_4BPPV1_Format: CompressedPixelFormat; + export const RGBA_PVRTC_2BPPV1_Format: CompressedPixelFormat; + + // ETC compressed texture formats + export const RGB_ETC1_Format: CompressedPixelFormat; // Loop styles for AnimationAction export enum AnimationActionLoopStyles { } - export var LoopOnce: AnimationActionLoopStyles; - export var LoopRepeat: AnimationActionLoopStyles; - export var LoopPingPong: AnimationActionLoopStyles; + export const LoopOnce: AnimationActionLoopStyles; + export const LoopRepeat: AnimationActionLoopStyles; + export const LoopPingPong: AnimationActionLoopStyles; + + // Interpolation + export enum InterpolationModes { } + export const InterpolateDiscrete: InterpolationModes; + export const InterpolateLinear: InterpolationModes; + export const InterpolateSmooth: InterpolationModes; + + // Interpolant ending modes + export enum InterpolationEndingModes { } + export const ZeroCurvatureEnding: InterpolationEndingModes; + export const ZeroSlopeEnding: InterpolationEndingModes; + export const WrapAroundEnding: InterpolationEndingModes; + + // Triangle Draw modes + export enum TrianglesDrawModes { } + export const TrianglesDrawModesMode: TrianglesDrawModes; + export const TriangleStripDrawMode: TrianglesDrawModes; + export const TriangleFanDrawMode: TrianglesDrawModes; // log handlers export function warn(message?: any, ...optionalParams: any[]): void; @@ -176,188 +196,170 @@ declare namespace THREE { export function log(message?: any, ...optionalParams: any[]): void; // Animation //////////////////////////////////////////////////////////////////////////////////////// - export class AnimationAction { - constructor(clip: AnimationClip, startTime?: number, timeScale?: number, weight?: number, loop?: boolean); - - clip: AnimationClip - localRoot: Mesh; - startTime: number; - timeScale: number; - weight: number; - loop: AnimationActionLoopStyles; - loopCount: number; - enabled: boolean; - actionTime: number; - clipTime: number; - propertyBindings: PropertyBinding[]; - - setLocalRoot( localRoot: Mesh ): AnimationAction; - updateTime( clipDeltaTime: number ): number; - syncWith( action: AnimationAction ): AnimationAction; - warpToDuration( duration: number ): AnimationAction; - init( time: number ): AnimationAction; - update( clipDeltaTime: number ): any[]; - getTimeScaleAt( time: number ): number; - getWeightAt( time: number ): number; - } export class AnimationClip { - constructor( name: string, duration?: number, tracks?: KeyframeTrack[] ); + constructor( name?: string, duration?: number, tracks?: KeyframeTrack[] ); name: string; tracks: KeyframeTrack[]; duration: number; results: any[]; - getAt(clipTime: number): any[]; + resetDuration(): void; trim(): AnimationClip; optimize(): AnimationClip; static CreateFromMorphTargetSequence( name: string, morphTargetSequence: MorphTarget[], fps: number ): AnimationClip; - findByName( clipArray: AnimationClip, name: string ): AnimationClip; + static findByName( clipArray: AnimationClip, name: string ): AnimationClip; static CreateClipsFromMorphTargetSequences( morphTargets: MorphTarget[], fps: number ): AnimationClip[]; - parse( json: any ): AnimationClip; - parseAnimation( animation: any, bones: Bone[], nodeName: string ): AnimationClip; + static parse( json: any ): AnimationClip; + static parseAnimation( animation: any, bones: Bone[], nodeName: string ): AnimationClip; + static toJSON(): any; } export class AnimationMixer { - constructor( root: any ); + constructor(root: any); - root: any; time: number; timeScale: number; - actions: AnimationAction; - propertyBindingMap: any; - addAction( action: AnimationAction ): void; - removeAllActions(): AnimationMixer; - removeAction( action: AnimationAction ): AnimationMixer; - findActionByName( name: string ): AnimationAction; - play( action: AnimationAction, optionalFadeInDuration?: number ): AnimationMixer; - fadeOut( action: AnimationAction, duration: number ): AnimationMixer; - fadeIn( action: AnimationAction, duration: number ): AnimationMixer; - warp( action: AnimationAction, startTimeScale: NumberKeyframeTrack, endTimeScale: NumberKeyframeTrack, duration: number ): AnimationMixer; - crossFade( fadeOutAction: AnimationAction, fadeInAction: AnimationAction, duration: number, warp: boolean ): AnimationMixer; - update( deltaTime: number ): AnimationMixer; + clipAction(clip: AnimationClip, root?: any): any; // returns THREE.AnimationMixer._Action + existingAction(clip: AnimationClip, root?: any): any; /// returns THREE.AnimationMixer._Action + stopAllAction(clip: AnimationClip, root?: any): AnimationMixer; + update(deltaTime: number): AnimationMixer; + getRoot(): any; + uncacheClip(clip: AnimationClip): void; + uncacheRoot(root: any): void; + uncazcheAction(clip: AnimationClip, root?: any): void; } - export var AnimationUtils: { - getEqualsFunc( exemplarValue: any ): boolean; - clone(exemplarValue: T): T; - lerp( a: any, b: any, alpha: number, interTrack: boolean ): any; - lerp_object( a: any, b: any, alpha: number ): any; - slerp_object( a: any, b: any, alpha: number ): any; - lerp_number( a: any, b: any, alpha: number ): any; - lerp_boolean( a: any, b: any, alpha: number ): any; - lerp_boolean_immediate( a: any, b: any, alpha: number ): any; - lerp_string( a: any, b: any, alpha: number ): any; - lerp_string_immediate( a: any, b: any, alpha: number ): any; - getLerpFunc( exemplarValue: any, interTrack: boolean ): Function; - }; + export class AnimationObjectGroup { + constructor(...args: any[]); + + uuid: string; + stats: { + bindingsPerObject: number; + objects: { + total: number; + inUse: number; + } + }; + + add(...args: any[]): void; + remove(...args: any[]): void; + uncache(...args: any[]): void; + } + + export namespace AnimationUtils { + export function arraySlice(array: any, from: number, to: number): any; + export function convertArray(array: any, type: any, forceClone: boolean): any; + export function isTypedArray(object: any): boolean; + export function getKeyFrameOrder(times: number): number[]; + export function sortedArray(values: any[], stride: number, order: number[]): any[]; + export function flattenJSON(jsonKeys: string[], times: any[], values: any[], valuePropertyName: string): void; + } export class KeyframeTrack { - constructor(name: string, keys: any[]); + constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); name: string; - keys: any[]; - lastIndex: number; + times: any[]; + values: any[]; + + ValueTypeName: string; + TimeBufferType: Float32Array; + ValueBufferType: Float32Array; + + DefaultInterpolation: InterpolationModes; + + InterpolantFactoryMethodDiscrete(result: any): DiscreteInterpolant; + InterpolantFactoryMethodLinear(result: any): LinearInterpolant; + InterpolantFactoryMethodSmooth(result: any): CubicInterpolant; + + setInterpolation(interpolation: InterpolationModes): void; + getInterpolation(): InterpolationModes; + + getValuesize(): number; - getAt( time: number ): any; shift( timeOffset: number ): KeyframeTrack; scale( timeScale: number ): KeyframeTrack; trim( startTime: number, endTime: number ): KeyframeTrack; - validate(): KeyframeTrack; + validate(): boolean; optimize(): KeyframeTrack; - keyComparator(key0: KeyframeTrack, key1: KeyframeTrack): number; - parse( json: any ): KeyframeTrack; - GetTrackTypeForTypeName( typeName: string ): any; + static parse(json: any): KeyframeTrack; + static toJSON(track: KeyframeTrack): any; } export class PropertyBinding { - constructor( rootNode: any, trackName: string ); + constructor(rootNode: any, path: string, parsedPath?: any); - rootNode: any; - trackName: string; - referenceCount: number; - originalValue: any; - directoryName: string; - nodeName: string; - objectName: string; - objectIndex: number; - propertyName: string; - propertyIndex: number; + path: string; + parsedPath: any; node: any; - cumulativeValue: number; - cumulativeWeight: number; + rootNode: any; - reset(): void; - accumulate( value: any, weight: number ): void; - unbind(): void; + getValue(targetArray: any, offset: number): any; + setValue(sourceArray: any, offset: number): void; bind(): void; - apply(): void; - parseTrackName( trackName: string ): any; - findNode( root: any, nodeName: string ): any; + unbind(): void; + + BindingType: { [bindingType: string]: number }; + Versioning: { [versioning: string]: number }; + + GetterByBindingType: Function[]; + SetterByBindingTypeAndVersioning: Array; + + static create(root: any, path: any, parsedPath?: any): PropertyBinding|PropertyBinding.Composite; + static parseTrackName(trackName: string): any; + static findNode(root: any, nodeName: string): any; + } + + export namespace PropertyBinding { + export class Composite { + constructor(targetGroup: any, path: any, parsedPath?: any); + + getValue(array: any, offset: number): any; + setValue(array: any, offset: number): void; + bind(): void; + unbind(): void; + } + } + + export class PropertyMixer { + constructor(binding: any, typeName: string, valueSize: number); + + binding: any; + valueSize: number; + buffer: any; + cumulativeWeight: number; + useCount: number; + referenceCount: number; + + accumulate(accuIndex: number, weight: number): void; + apply(accuIndex: number): void; + saveOriginalState(): void; + restoreOriginalState(): void; } export class BooleanKeyframeTrack extends KeyframeTrack { - constructor(name: string, keys: any[]); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): BooleanKeyframeTrack; - parse( json: any ): BooleanKeyframeTrack; + constructor(name: string, times: any[], values: any[]); } - export class NumberKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): NumberKeyframeTrack; - parse( json: any ): NumberKeyframeTrack; + export class NumberKeyframeTrack extends KeyframeTrack { + constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); } - export class QuaternionKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): QuaternionKeyframeTrack; - parse( json: any ): QuaternionKeyframeTrack; + export class QuaternionKeyframeTrack extends KeyframeTrack { + constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); } - export class StringKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): StringKeyframeTrack; - parse( json: any ): StringKeyframeTrack; + export class StringKeyframeTrack extends KeyframeTrack { + constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); } - export class VectorKeyframeTrack { - constructor(); - - result: any; - - setResult( value: any ): void; - lerpValues( value0: any, value1: any, alpha: number ): any; - compareValues( value0: any, value1: any ): boolean; - clone(): VectorKeyframeTrack; - parse( json: any ): VectorKeyframeTrack; + export class VectorKeyframeTrack extends KeyframeTrack { + constructor(name: string, times: any[], values: any[], interpolation: InterpolationModes); } // Cameras //////////////////////////////////////////////////////////////////////////////////////// @@ -394,12 +396,11 @@ declare namespace THREE { } export class CubeCamera extends Object3D { - constructor( near?: number, far?: number, cubeResolution?: number); + constructor(near?: number, far?: number, cubeResolution?: number); renderTarget: WebGLRenderTargetCube; - updateCubeMap( renderer: Renderer, scene: Scene ): void; - + updateCubeMap(renderer: Renderer, scene: Scene): void; } /** @@ -459,8 +460,8 @@ declare namespace THREE { */ updateProjectionMatrix(): void; clone(): OrthographicCamera; - copy( source: OrthographicCamera ): OrthographicCamera; - toJSON( meta?: any ): any; + copy(source: OrthographicCamera): OrthographicCamera; + toJSON(meta?: any): any; } /** @@ -481,6 +482,7 @@ declare namespace THREE { */ constructor(fov?: number, aspect?: number, near?: number, far?: number); + focalLength: number; zoom: number; /** @@ -555,8 +557,18 @@ declare namespace THREE { */ updateProjectionMatrix(): void; clone(): PerspectiveCamera; - copy( source: PerspectiveCamera ): PerspectiveCamera; - toJSON( meta?: any ): any; + copy(source: PerspectiveCamera): PerspectiveCamera; + toJSON(meta?: any): any; + } + + export class StereoCamera extends Camera { + constructor(); + + aspect: number; + cameraL: PerspectiveCamera; + cameraR: PerspectiveCamera; + + update(camera: PerspectiveCamera): void; } // Core /////////////////////////////////////////////////////////////////////////////////////////////// @@ -573,10 +585,7 @@ declare namespace THREE { dynamic: boolean; updateRange: {offset:number, count:number}; version: number; - needsUpdate: boolean; - /** Deprecated, use count instead */ - length: number; count: number; setDynamic(dynamic: boolean): BufferAttribute; @@ -602,53 +611,49 @@ declare namespace THREE { 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 } - // deprecated (are these actually deprecated?) - export class Int8Attribute extends BufferAttribute{ + export class Int8Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Uint8Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Uint8ClampedAttribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Int16Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Uint16Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Int32Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Uint32Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Float32Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } - // deprecated export class Float64Attribute extends BufferAttribute { constructor(array: any, itemSize: number); } + // deprecated, use new THREE.BufferAttribute().setDynamic( true ) + export class DynamicBufferAttribute extends BufferAttribute {} + /** * This is a superefficent class for geometries because it saves all data in buffers. * It reduces memory costs and cpu cycles. But it is not as easy to work with because of all the nessecary buffer calculations. @@ -674,32 +679,21 @@ declare namespace THREE { index: BufferAttribute; attributes: BufferAttribute|InterleavedBufferAttribute[]; morphAttributes: any; + drawcalls: any; // deprecated, use groups + offsets: any; // deprecated, use groups groups: {start: number, count: number, materialIndex?: number}[]; boundingBox: Box3; boundingSphere: BoundingSphere; drawRange: { start: number, count: number }; - /** Deprecated. */ - addIndex( index: BufferAttribute ): void; - getIndex(): BufferAttribute; setIndex( index: BufferAttribute ): void; - /** Deprecated. This overloaded method is deprecated. */ - addAttribute(name: string, array: any, itemSize: number): any; - addAttribute(name: string, attribute: BufferAttribute|InterleavedBufferAttribute): void; + addAttribute(name: string, attribute: BufferAttribute|InterleavedBufferAttribute): BufferGeometry; + getAttribute(name: string): BufferAttribute|InterleavedBufferAttribute; - removeAttribute(name: string): void; + removeAttribute(name: string): BufferGeometry; - /** Deprecated. */ - drawcalls(): any; - /** Deprecated. */ - offsets(): any; - - /** Deprecated. Use addGroup */ - addDrawCall(start: number, count: number, index?: number): void; - /** Deprecated. */ - clearDrawCalls(): void; addGroup(start: number, count: number, materialIndex?: number): void; clearGroups(): void; @@ -724,7 +718,7 @@ declare namespace THREE { fromGeometry(geometry: Geometry, settings?: any): BufferGeometry; - fromDirectGeometry( geometry: DirectGeometry ): BufferGeometry; + fromDirectGeometry(geometry: DirectGeometry): BufferGeometry; /** * Computes bounding box of the geometry, updating Geometry.boundingBox attribute. @@ -738,17 +732,16 @@ declare namespace THREE { */ computeBoundingSphere(): void; - // deprecated - computeFaceNormals(): void; - /** * Computes vertex normals by averaging face normals. */ computeVertexNormals(): void; - computeOffsets(size: number): void; merge(geometry: BufferGeometry, offset: number): BufferGeometry; normalizeNormals(): void; + + toNonIndexed(): BufferGeometry; + toJSON(): any; clone(): BufferGeometry; copy(source: BufferGeometry): BufferGeometry; @@ -759,23 +752,17 @@ declare namespace THREE { */ dispose(): void; - // EventDispatcher mixins addEventListener(type: string, listener: (event: any) => void ): void; hasEventListener(type: string, listener: (event: any) => void): void; removeEventListener(type: string, listener: (event: any) => void): void; dispatchEvent(event: { type: string; target: any; }): void; - } - export class Channels { - constructor(); - - mask: number; - - set( channel: number ): void; - enable( channel: number ): void; - toggle( channel: number ): void; - disable( channel: number ): void; + addIndex(index: any): void; // deprecated, use setIndex() + addAttribute(name: any, array: any, itemSize: any): any; // deprecated + addDrawCall(start: any, count: any, indexOffset?: any): void; // deprecated, use addGroup() + clearDrawCalls(): void; // deprecated, use clearGroups() + computeFaceNormals(): void; // deprecated } /** @@ -879,6 +866,7 @@ declare namespace THREE { dispatchEvent(event: { type: string; target: any; }): void; } + /** * JavaScript events for custom objects * @@ -910,6 +898,8 @@ declare namespace THREE { */ constructor(); + apply(object: any): void; + /** * Adds a listener to an event type. * @param type The type of the listener that gets removed. @@ -997,19 +987,17 @@ declare namespace THREE { */ vertexColors: Color[]; - /** - * Array of 4 vertex tangets. - */ - vertexTangents: number[]; - /** * Material index (points to {@link Geometry.materials}). */ materialIndex: number; clone(): Face3; + copy(source: Face3): Face3; } + export class Face4 extends Face3 {} // deprecated, use Face3 + export interface MorphTarget { name: string; vertices: Vector3[]; @@ -1029,6 +1017,8 @@ declare namespace THREE { radius: number; } + export let GeometryIdCount: number; + /** * Base class for geometries * @@ -1085,7 +1075,7 @@ declare namespace THREE { * Each UV layer is an array of UV matching order and number of vertices in faces. * To signal an update in this array, Geometry.uvsNeedUpdate needs to be set to true. */ - faceVertexUvs: Vector2[][][]; + faceVertexUvs: Vector2[][]; /** * Array of morph targets. Each morph target is a Javascript object: @@ -1176,12 +1166,8 @@ declare namespace THREE { scale(x: number, y: number, z: number): Geometry; lookAt( vector: Vector3 ): void; - fromBufferGeometry(geometry: BufferGeometry): Geometry; - /** - * - */ center(): Vector3; normalize(): Geometry; @@ -1215,9 +1201,9 @@ declare namespace THREE { */ computeBoundingSphere(): void; - merge( geometry: Geometry, matrix: Matrix, materialIndexOffset?: number): void; + merge(geometry: Geometry, matrix: Matrix, materialIndexOffset?: number): void; - mergeMesh( mesh: Mesh ): void; + mergeMesh(mesh: Mesh): void; /** * Checks for duplicate vertices using hashmap. @@ -1255,11 +1241,17 @@ declare namespace THREE { dispatchEvent(event: { type: string; target: any; }): void; } + export namespace GeometryUtils { // deprecated + export function merge(goemetry1: any, goemetry2: any, materialIndexOffset?: any): any; // deprecated, use geometry.merge( geometry2, matrix, materialIndexOffset ) + export function center(geometry: any): any; // deprecated, use geometry.center() + } + /** * @see src/core/InstancedBufferAttribute.js */ export class InstancedBufferAttribute extends BufferAttribute { constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); + meshPerAttribute: number; clone(): InstancedBufferAttribute; @@ -1271,33 +1263,25 @@ declare namespace THREE { */ export class InstancedBufferGeometry extends BufferGeometry { constructor(); - groups: {start:number, count:number, instances:number}[]; - addGroup(start: number, count: number, instances: number): void; + groups: {start:number, count:number, instances:number}[]; + maxInstancedCount: number; + + addGroup(start: number, count: number, instances: number): void; clone(): InstancedBufferGeometry; copy(source: InstancedBufferGeometry): InstancedBufferGeometry; } - /** - * @see src/core/InstancedInterleavedBuffer.js - */ - export class InstancedInterleavedBuffer extends InterleavedBuffer { - constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); - meshPerAttribute: number; - - clone(): InstancedInterleavedBuffer; - copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; - } - /** * @see src/core/InterleavedBuffer.js */ export class InterleavedBuffer { constructor(array: ArrayLike, stride: number); + array: ArrayLike; stride: number; dynamic: boolean; - updateRange: {offset:number, count:number}; + updateRange: { offset: number; count: number }; version: number; length: number; count: number; @@ -1311,6 +1295,18 @@ declare namespace THREE { clone(): InterleavedBuffer; } + /** + * @see src/core/InstancedInterleavedBuffer.js + */ + export class InstancedInterleavedBuffer extends InterleavedBuffer { + constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); + + meshPerAttribute: number; + + clone(): InstancedInterleavedBuffer; + copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; + } + /** * @see src/core/InterleavedBufferAttribute.js */ @@ -1321,8 +1317,6 @@ declare namespace THREE { data: InterleavedBuffer; itemSize: number; offset: number; - /** Deprecated, use count instead */ - length: number; count: number; getX(index: number): number; @@ -1336,8 +1330,12 @@ declare namespace THREE { setXY(index: number, x: number, y: number): InterleavedBufferAttribute; setXYZ(index: number, x: number, y: number, z: number): InterleavedBufferAttribute; setXYZW(index: number, x: number, y: number, z: number, w: number): InterleavedBufferAttribute; + + length: number; // deprecated, use count instead } + export let Object3DIdCount: number; + /** * Base class for scene graph objects */ @@ -1366,8 +1364,6 @@ declare namespace THREE { */ parent: Object3D; - channels: Channels; - /** * Array with object's children. */ @@ -1387,6 +1383,7 @@ declare namespace THREE { * Object's local rotation (Euler angles), in radians. */ rotation: Euler; + eulerOrder: string; // deprecated, use rotation.order /** * Global rotation. @@ -1427,6 +1424,7 @@ declare namespace THREE { */ matrixWorldNeedsUpdate: boolean; + layers: Layers; /** * Object gets rendered if true. */ @@ -1458,7 +1456,7 @@ declare namespace THREE { * */ static DefaultUp: Vector3; - static DefaultMatrixAutoUpdate: Vector3; + static DefaultMatrixAutoUpdate: boolean; /** * This updates the position, rotation and scale with the matrix. @@ -1473,7 +1471,7 @@ declare namespace THREE { /** * */ - setRotationFromEuler(euler: Euler ): void; + setRotationFromEuler(euler: Euler): void; /** * @@ -1483,7 +1481,7 @@ declare namespace THREE { /** * */ - setRotationFromQuaternion( q: Quaternion ): void; + setRotationFromQuaternion(q: Quaternion): void; /** * Rotate an object along an axis in object space. The axis is assumed to be normalized. @@ -1515,13 +1513,7 @@ declare namespace THREE { * @param distance The distance to translate. */ translateOnAxis(axis: Vector3, distance: number): Object3D; - - /** - * - * @param distance - * @param axis - */ - translate( distance: number, axis: Vector3 ): Object3D; + translate(distance: number, axis: Vector3): Object3D; // deprecated, use translateOnAxis(axis, distance) /** * Translates object along x axis by distance. @@ -1569,9 +1561,6 @@ declare namespace THREE { */ remove(object: Object3D): void; - /* deprecated */ - getChildByName( name: string ): Object3D; - /** * Searches through the object's children and returns the first with a matching id, optionally recursive. * @param id Unique number of the object instance @@ -1594,11 +1583,11 @@ declare namespace THREE { raycast(raycaster: Raycaster, intersects: any): void; - traverse(callback: (object: Object3D) => void): void; + traverse(callback: (object: Object3D) => any): void; - traverseVisible(callback: (object: Object3D) => void): void; + traverseVisible(callback: (object: Object3D) => any): void; - traverseAncestors(callback: (object: Object3D) => void): void; + traverseAncestors(callback: (object: Object3D) => any): void; /** * Updates local transform. @@ -1610,7 +1599,7 @@ declare namespace THREE { */ updateMatrixWorld(force: boolean): void; - toJSON(meta?: any): any; + toJSON(meta?: { geometries: any, materials: any, textures: any, images: any }): any; clone(recursive?: boolean): Object3D; @@ -1627,6 +1616,7 @@ declare namespace THREE { removeEventListener(type: string, listener: (event: any) => void): void; dispatchEvent(event: { type: string; target: any; }): void; + getChildByName(name: string): Object3D; // deprecated, use getObjectByName() } export interface Intersection { @@ -1643,7 +1633,7 @@ declare namespace THREE { Mesh?: any; Line?: any; LOD?: any; - Points?: any; + Points?: { threshold: number }; Sprite?: any; } @@ -1656,38 +1646,58 @@ declare namespace THREE { params: RaycasterParameters; precision: number; linePrecision: number; + set(origin: Vector3, direction: Vector3): void; setFromCamera(coords: { x: number; y: number;}, camera: Camera ): void; intersectObject(object: Object3D, recursive?: boolean): Intersection[]; intersectObjects(objects: Object3D[], recursive?: boolean): Intersection[]; } + export class Layers { + constructor(); + + mask: number; + + set(channel: number): void; + enable(channel: number): void; + toggle(channel: number): void; + disable(channel: number): void; + test(layers: Layers): boolean; + } + + export class Font { + constructor(data: any); + + data: any; + + generateShapes(text: string, size: number, divisions: number): any[]; + } + // Lights ////////////////////////////////////////////////////////////////////////////////// /** * Abstract base class for lights. */ export class Light extends Object3D { - constructor(hex?: number|string); + constructor(hex?: number|string, intensity?: number); color: Color; + intensity: number; receiveShadow: boolean; + shadow: LightShadow; + shadowCameraFov: any; // deprecated, use shadow.camera.fov + shadowCameraLeft: any; // deprecated, use shadow.camera.left + shadowCameraRight: any; // deprecated, use shadow.camera.right + shadowCameraTop: any; // deprecated, use shadow.camera.top + shadowCameraBottom: any; // deprecated, use shadow.camera.bottom + shadowCameraNear: any; // deprecated, use shadow.camera.near + shadowCameraFar: any; // deprecated, use shadow.camera.far + shadowBias: any; // deprecated, use shadow.bias + shadowMapWidth: any; // deprecated, use shadow.mapSize.width + shadowMapHeight: any; // deprecated, use shadow.mapSize.height - shadowCameraFov: number; - shadowCameraLeft: number; - shadowCameraRight: number; - shadowCameraTop: number; - shadowCameraBottom: number; - shadowCameraNear: number; - shadowCameraFar: number; - shadowBias: number; - shadowDarkness: number; - shadowMapWidth: number; - shadowMapHeight: number; - + copy(source: Light): Light; clone(recursive?: boolean): Light; - copy( source: Light ): Light; - toJSON( meta: any ): any; } export class LightShadow { @@ -1695,13 +1705,13 @@ declare namespace THREE { camera: Camera; bias: number; - darkness: number; + radius: number; mapSize: Vector2; map: RenderTarget; matrix: Matrix4; - copy(source: LightShadow): void; - clone(): LightShadow; + copy(source: LightShadow): LightShadow; + clone(recursive?: boolean): LightShadow; } /** @@ -1718,10 +1728,12 @@ declare namespace THREE { * This creates a Ambientlight with a color. * @param hex Numeric value of the RGB component of the color. */ - constructor(hex?: number|string); + constructor(hex?: number|string, intensity?: number); + + castShadow: boolean; - clone(recursive?: boolean): AmbientLight; copy(source: AmbientLight): AmbientLight; + clone(recursive?: boolean): AmbientLight; } /** @@ -1736,7 +1748,6 @@ declare namespace THREE { * @see src/lights/DirectionalLight.js */ export class DirectionalLight extends Light { - constructor(hex?: number|string, intensity?: number); /** @@ -1752,8 +1763,8 @@ declare namespace THREE { shadow: LightShadow; - clone(recursive?: boolean): DirectionalLight; copy(source: DirectionalLight): DirectionalLight; + clone(recursive?: boolean): HemisphereLight; } export class HemisphereLight extends Light { @@ -1762,8 +1773,8 @@ declare namespace THREE { groundColor: Color; intensity: number; - clone(recursive?: boolean): HemisphereLight; copy(source: HemisphereLight): HemisphereLight; + clone(recursive?: boolean): HemisphereLight; } /** @@ -1793,8 +1804,8 @@ declare namespace THREE { shadow: LightShadow; - clone(recursive?: boolean): PointLight; copy(source: PointLight): PointLight; + clone(recursive?: boolean): PointLight; } /** @@ -1843,11 +1854,6 @@ declare namespace THREE { // Loaders ////////////////////////////////////////////////////////////////////////////////// - export interface Progress { - total: number; - loaded: number; - } - /** * Base class for implementing loaders. * @@ -1896,54 +1902,32 @@ declare namespace THREE { } export interface LoaderHandler{ - handlers:any[]; - add(regex:string, loader:Loader):void; - get(file: string):Loader; + handlers: any[]; + + add(regex: string, loader: Loader): void; + get(file: string): Loader; } - export class BinaryTextureLoader { + export class XHRLoader { constructor(manager?: LoadingManager); manager: LoadingManager; - load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; + path: string; + responseType: string; + withCredentials: boolean; + + load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): any; + setPath(path: string): void; + setResponseType(responseType: string): void; + setWithCredentials(withCredentials: boolean): void; } - export class BufferGeometryLoader { + export class FontLoader { constructor(manager?: LoadingManager); manager: LoadingManager; - load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - parse(json: any): BufferGeometry; - } - - export interface Cache { - enabled: boolean; - files: any[]; - - add(key: string, file: any): void; - get(key: string): any; - remove(key: string): void; - clear(): void; - } - export var Cache: Cache; - - export class CompressedTextureLoader{ - constructor(manager?: LoadingManager); - - manager: LoadingManager; - load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; - } - - export class CubeTextureLoader { - constructor(manager?: LoadingManager); - - manager: LoadingManager; - load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - setCrossOrigin(crossOrigin: string): void; + load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; } /** @@ -1953,17 +1937,17 @@ declare namespace THREE { export class ImageLoader { constructor(manager?: LoadingManager); - cache: Cache; manager: LoadingManager; crossOrigin: string; + path: string; /** * Begin loading from url * @param url */ load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement; - setCrossOrigin(crossOrigin: string): void; + setPath(value: any): void; } /** @@ -1971,12 +1955,12 @@ declare namespace THREE { */ export class JSONLoader extends Loader { constructor(manager?: LoadingManager); + manager: LoadingManager; withCredentials: boolean; + statusDomElement: HTMLElement; // readonly and deprecated load(url: string, onLoad?: (geometry: Geometry, materials: Material[]) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; - - setCrossOrigin(crossOrigin: string): void; setTexturePath( value: string ): void; parse(json: any, texturePath?: string): { geometry: Geometry; materials?: Material[] }; } @@ -2012,18 +1996,26 @@ declare namespace THREE { itemError(url: string): void; } - export var DefaultLoadingManager: LoadingManager; + export const DefaultLoadingManager: LoadingManager; + + export class BufferGeometryLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + + load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + parse(json: any): BufferGeometry; + } export class MaterialLoader { constructor(manager?: LoadingManager); manager: LoadingManager; - textures: { [key:string]:Texture }; + textures: { [key: string]: Texture }; load(url: string, onLoad: (material: Material) => void): void; - setCrossOrigin(crossOrigin: string): void; - setTextures(textures: { [key:string]:Texture }): void; - getTexture( name: string ):Texture; + setTextures(textures: { [key: string]: Texture }): void; + getTexture(name: string): Texture; parse(json: any): Material; } @@ -2032,6 +2024,7 @@ declare namespace THREE { manager: LoadingManager; texturePass: string; + crossOrigin: string; load(url: string, onLoad?: (object: Object3D) => void): void; setTexturePath( value: string ): void; @@ -2039,10 +2032,10 @@ declare namespace THREE { parse(json: any, onLoad?: (object: Object3D) => void): T; parseGeometries(json: any): any[]; // Array of BufferGeometry or Geometry or Geometry2. parseMaterials(json: any, textures: Texture[]): Material[]; // Array of Classes that inherits from Matrial. - parseImages( json: any, onLoad: () => void ): any[]; - parseTextures( json: any, images: any ): Texture[]; + parseAnimations(json: any): AnimationClip[]; + parseImages(json: any, onLoad: () => void): any[]; + parseTextures(json: any, images: any): Texture[]; parseObject(data: any, geometries: any[], materials: Material[]): T; - } /** @@ -2054,6 +2047,7 @@ declare namespace THREE { manager: LoadingManager; crossOrigin: string; + path: string; /** * Begin loading from url @@ -2062,23 +2056,53 @@ declare namespace THREE { */ load(url: string, onLoad?: (texture: Texture) => void): Texture; setCrossOrigin(crossOrigin: string): void; + setPath(path: string): void; } - export class XHRLoader { + export class CubeTextureLoader { constructor(manager?: LoadingManager); - cache: Cache; manager: LoadingManager; - responseType: string; - crossOrigin: string; + corssOrigin: string; + path: string; - load(url: string, onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): any; - setResponseType(responseType: string): void; + load(urls: Array, onLoad?: (texture: CubeTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; setCrossOrigin(crossOrigin: string): void; - setWithCredentials( withCredentials: string ): void; + setPath(path: string): void; + } + + export class BinaryTextureLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + + load(url: string, onLoad: (dataTexture: DataTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + } + export class DataTextureLoader extends BinaryTextureLoader {} + + export class CompressedTextureLoader { + constructor(manager?: LoadingManager); + + manager: LoadingManager; + path: string; + + load(url: string, onLoad: (texture: CompressedTexture) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void; + setPath(path: string): void; + } + + export namespace Cache { + export let enabled: boolean; + export let files: any; + + export function add(key: string, file: any): void; + export function get(key: string): any; + export function remove(key: string): void; + export function clear(): void; } // Materials ////////////////////////////////////////////////////////////////////////////////// + export let MaterialIdCount: number; + export interface MaterialParameters { name?: string; side?: Side; @@ -2088,15 +2112,20 @@ declare namespace THREE { blendSrc?: BlendingDstFactor; blendDst?: BlendingSrcFactor; blendEquation?: BlendingEquation; + blendSrcAlpha?: number; + blendDstAlpha?: number; + blendEquationAlpha?: number; + depthFunc?: DepthModes; depthTest?: boolean; depthWrite?: boolean; + colorWrite?: boolean; + precision?: number; polygonOffset?: boolean; polygonOffsetFactor?: number; polygonOffsetUnits?: number; alphaTest?: number; overdraw?: number; visible?: boolean; - needsUpdate?: boolean; } /** @@ -2213,10 +2242,12 @@ declare namespace THREE { */ needsUpdate: boolean; - setValues(values: Object): void; + warpRGB: Color; // deprecated, returns a new Color intance + + setValues(parameters: MaterialParameters): void; toJSON(meta?: any): any; clone(): Material; - clone(source?:Material): Material; + copy(source: Material): Material; update(): void; dispose(): void; @@ -2246,6 +2277,7 @@ declare namespace THREE { vertexColors: Colors; fog: boolean; + setValues(parameters: LineBasicMaterialParameters): void; clone(): LineBasicMaterial; copy(source: LineBasicMaterial): LineBasicMaterial; } @@ -2271,6 +2303,7 @@ declare namespace THREE { vertexColors: Colors; fog: boolean; + setValues(parameters: LineDashedMaterialParameters): void; clone(): LineDashedMaterial; copy(source: LineDashedMaterial): LineDashedMaterial; } @@ -2278,7 +2311,7 @@ declare namespace THREE { /** * parameters is an object with one or more properties defining the material's appearance. */ - export interface MeshBasicMaterialParameters extends MaterialParameters{ + export interface MeshBasicMaterialParameters extends MaterialParameters { color?: number|string; opacity?: number; map?: Texture; @@ -2296,6 +2329,8 @@ declare namespace THREE { depthWrite?: boolean; wireframe?: boolean; wireframeLinewidth?: number; + wireframeLinecap?: string; + wireframeLinejoin?: string; vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; @@ -2325,11 +2360,12 @@ declare namespace THREE { skinning: boolean; morphTargets: boolean; + setValues(parameters: MeshBasicMaterialParameters): void; clone(): MeshBasicMaterial; copy(source: MeshBasicMaterial): MeshBasicMaterial; } - export interface MeshDepthMaterialParameters extends MaterialParameters{ + export interface MeshDepthMaterialParameters extends MaterialParameters { wireframe?: boolean; wireframeLinewidth?: number; } @@ -2340,15 +2376,21 @@ declare namespace THREE { wireframe: boolean; wireframeLinewidth: number; + setValues(parameters: MeshDepthMaterialParameters): void; clone(): MeshDepthMaterial; copy(source: MeshDepthMaterial): MeshDepthMaterial; } - export interface MeshLambertMaterialParameters extends MaterialParameters{ + export interface MeshLambertMaterialParameters extends MaterialParameters { color?: number|string; - emissive?: number; - opacity?: number; + emissive?: number|string; + emissiveIntensity?: number; + emissiveMap?: Texture; map?: Texture; + lighhtMap?: Texture; + lightMapIntensity?: number; + aoMap?: Texture; + aoMapIntensity?: number; specularMap?: Texture; alphaMap?: Texture; envMap?: Texture; @@ -2358,6 +2400,8 @@ declare namespace THREE { fog?: boolean; wireframe?: boolean; wireframeLinewidth?: number; + wireframeLinecap?: string; + wireframeLinejoin?: string; vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; @@ -2368,8 +2412,14 @@ declare namespace THREE { constructor(parameters?: MeshLambertMaterialParameters); color: Color; - emissive: Color; + emissive: number|string; + emissiveIntensity: number; + emissiveMap: Texture; map: Texture; + lighhtMap: Texture; + lightMapIntensity: number; + aoMap: Texture; + aoMapIntensity: number; specularMap: Texture; alphaMap: Texture; envMap: Texture; @@ -2386,22 +2436,94 @@ declare namespace THREE { morphTargets: boolean; morphNormals: boolean; + setValues(parameters: MeshLambertMaterialParameters): void; clone(): MeshLambertMaterial; copy(source: MeshLambertMaterial): MeshLambertMaterial; } - export interface MeshNormalMaterialParameters extends MaterialParameters{ - opacity?: number; + export interface MeshStandardMaterialParameters extends MaterialParameters { + color?: number|string; + roughtness?: number; + metalness?: number; + lighhtMap?: Texture; + lightMapIntensity?: number; + aoMap?: Texture; + aoMapIntensity?: number; + emissive?: Color; + emissiveIntensity?: number; + emissiveMap?: Texture; + bumpMap?: Texture; + bumpScale?: number; + normalMap?: Texture; + normalScale?: number; + displacementMap?: Texture; + displacementScale?: number; + displacementBias?: number; + roughtnessMap?: Texture; + metalMap?: Texture; + alphaMap?: Texture; + envMap?: Texture; + envMapIntensity?: number; + refractionRatio?: number; shading?: Shading; - blending?: Blending; - depthTest?: boolean; - depthWrite?: boolean; + blending: Blending; + wireframe?: boolean; + wireframeLinewidth?: number; + vertexColors?: Colors; + skinning?: boolean; + morphTargets?: boolean; + morphNormals?: boolean; + fog?: boolean; + } + export class MeshStandardMaterial extends Material { + constructor(parameters?: MeshStandardMaterialParameters); + + color: Color; + roughtness: number; + metalness: number; + map: Texture; + lighhtMap: Texture; + lightMapIntensity: number; + aoMap: Texture; + aoMapIntensity: number; + emissive: Color; + emissiveIntensity: number; + emissiveMap: Texture; + bumpMap: Texture; + bumpScale: number; + normalMap: Texture; + normalScale: number; + displacementMap: Texture; + displacementScale: number; + displacementBias: number; + roughtnessMap: Texture; + metalMap: Texture; + alphaMap: Texture; + envMap: Texture; + envMapIntensity: number; + refractionRatio: number; + shading: Shading; + blending: Blending; + wireframe: boolean; + wireframeLinewidth: number; + vertexColors: Colors; + skinning: boolean; + morphTargets: boolean; + morphNormals: boolean; + fog: boolean; + + setValues(parameters: MeshStandardMaterialParameters): void; + clone(): MeshStandardMaterial; + copy(source: MeshStandardMaterial): MeshStandardMaterial; + } + + export interface MeshNormalMaterialParameters extends MaterialParameters { /** Render geometry as wireframe. Default is false (i.e. render as smooth shaded). */ wireframe?: boolean; /** Controls wireframe thickness. Default is 1. */ wireframeLinewidth?: number; - + morphTargets?: boolean; } export class MeshNormalMaterial extends Material { @@ -2411,14 +2533,14 @@ declare namespace THREE { wireframeLinewidth: number; morphTargets: boolean; + setValues(parameters: MeshNormalMaterialParameters): void; clone(): MeshNormalMaterial; copy(source: MeshNormalMaterial): MeshNormalMaterial; } export interface MeshPhongMaterialParameters extends MaterialParameters { /** geometry color in hexadecimal. Default is 0xffffff. */ - color?: number | string; - emissive?: number; + color?: number|string; specular?: number; shininess?: number; opacity?: number; @@ -2427,6 +2549,8 @@ declare namespace THREE { lightMapIntensity?: number; aoMap?: Texture; aoMapIntensity?: number; + emissive?: number; + emissiveIntensity?: number; emissiveMap?: Texture; bumpMap?: Texture; bumpScale?: number; @@ -2447,6 +2571,8 @@ declare namespace THREE { depthWrite?: boolean; wireframe?: boolean; wireframeLinewidth?: number; + wireframeLinecap?: string; + wireframeLinejoin?: string; vertexColors?: Colors; skinning?: boolean; morphTargets?: boolean; @@ -2458,15 +2584,15 @@ declare namespace THREE { constructor(parameters?: MeshPhongMaterialParameters); color: Color; // diffuse - emissive: Color; specular: Color; shininess: number; - metal: boolean; map: Texture; lightMap: Texture; lightMapIntensity: number; aoMap: Texture; aoMapIntensity: number; + emissive: Color; + emissiveIntensity: number; emissiveMap: Texture; bumpMap: Texture; bumpScale: number; @@ -2491,7 +2617,9 @@ declare namespace THREE { skinning: boolean; morphTargets: boolean; morphNormals: boolean; + metal: boolean; // deprecated + setValues(parameters: MeshPhongMaterialParameters): void; clone(): MeshPhongMaterial; copy(source: MeshPhongMaterial): MeshPhongMaterial; } @@ -2500,18 +2628,16 @@ declare namespace THREE { // See tests/canvas/canvas_materials.ts. export class MultiMaterial extends Material { constructor(materials?: Material[]); + materials: Material[]; - toJSON(): any; + toJSON(meta: any): any; clone(): MultiMaterial; } - // deprecated - export class MeshFaceMaterial extends MultiMaterial { + export class MeshFaceMaterial extends MultiMaterial {} // deprecated, use MultiMaterial - } - - export interface PointsMaterialParameters extends MaterialParameters{ + export interface PointsMaterialParameters extends MaterialParameters { color?: number|string; opacity?: number; map?: Texture; @@ -2534,13 +2660,14 @@ declare namespace THREE { vertexColors: boolean; fog: boolean; + setValues(parameters: PointsMaterialParameters): void; clone(): PointsMaterial; copy(source: PointsMaterial): PointsMaterial; } - export class RawShaderMaterial extends ShaderMaterial { - constructor(parameters?: ShaderMaterialParameters); - } + export class PointCloudMaterial extends PointsMaterial {} // deprecated, use PointsMaterial + export class ParticleBasicMaterial extends PointsMaterial {} // deprecated, use PointsMaterial + export class ParticleSystemMaterial extends PointsMaterial {} // deprecated, use PointsMaterial export interface ShaderMaterialParameters extends MaterialParameters { defines?: any; @@ -2548,6 +2675,7 @@ declare namespace THREE { fragmentShader?: string; vertexShader?: string; shading?: Shading; + lineWidth?: number; blending?: Blending; depthTest?: boolean; depthWrite?: boolean; @@ -2578,15 +2706,21 @@ declare namespace THREE { skinning: boolean; morphTargets: boolean; morphNormals: boolean; - derivatives: boolean; + derivatives: any; // deprecated, use extensions.derivatives + extensions: { derivatives: boolean; fragDepth: boolean; drawBuffers: boolean; shaderTextureLOD: boolean }; defaultAttributeValues: any; index0AttributeName: string; + setValues(parameters: ShaderMaterialParameters): void; clone(): ShaderMaterial; copy(source: ShaderMaterial): ShaderMaterial; toJSON(meta: any): any; } + export class RawShaderMaterial extends ShaderMaterial { + constructor(parameters?: ShaderMaterialParameters); + } + export interface SpriteMaterialParameters extends MaterialParameters { color?: number|string; opacity?: number; @@ -2607,6 +2741,7 @@ declare namespace THREE { rotation: number; fog: boolean; + setValues(parameters: SpriteMaterialParameters): void; clone(): SpriteMaterial; copy(source: SpriteMaterial): SpriteMaterial; } @@ -2625,7 +2760,8 @@ declare namespace THREE { clone(): Box2; copy(box: Box2): Box2; makeEmpty(): Box2; - empty(): boolean; + empty(): any; // deprecated, use isEmpty() + isEmpty(): boolean; center(optionalTarget?: Vector2): Vector2; size(optionalTarget?: Vector2): Vector2; expandByPoint(point: Vector2): Box2; @@ -2634,13 +2770,15 @@ declare namespace THREE { containsPoint(point: Vector2): boolean; containsBox(box: Box2): boolean; getParameter(point: Vector2): Vector2; - isIntersectionBox(box: Box2): boolean; + intersectsBox(box: Box2): boolean; clampPoint(point: Vector2, optionalTarget?: Vector2): Vector2; distanceToPoint(point: Vector2): number; intersect(box: Box2): Box2; union(box: Box2): Box2; translate(offset: Vector2): Box2; equals(box: Box2): boolean; + + isIntersectionBox(b: any): any; // deprecated, use intersectsBox() } export class Box3 { @@ -2650,13 +2788,14 @@ declare namespace THREE { min: Vector3; set(min: Vector3, max: Vector3): Box3; + setFromArray(array: number[]): Box3; setFromPoints(points: Vector3[]): Box3; setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; clone(): Box3; copy(box: Box3): Box3; makeEmpty(): Box3; - empty(): boolean; + isEmpty(): boolean; center(optionalTarget?: Vector3): Vector3; size(optionalTarget?: Vector3): Vector3; expandByPoint(point: Vector3): Box3; @@ -2665,7 +2804,9 @@ declare namespace THREE { containsPoint(point: Vector3): boolean; containsBox(box: Box3): boolean; getParameter(point: Vector3): Vector3; - isIntersectionBox(box: Box3): boolean; + intersectsBox(box: Box3): boolean; + intersectsSphere(sphere: Sphere): boolean; + intersectsPlane(plane: Plane): boolean; clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; distanceToPoint(point: Vector3): number; getBoundingSphere(optionalTarget?: Sphere): Sphere; @@ -2674,6 +2815,10 @@ declare namespace THREE { applyMatrix4(matrix: Matrix4): Box3; translate(offset: Vector3): Box3; equals(box: Box3): boolean; + + empty(): any; // deprecated, use isEmpty() + isIntersectionBox(b: any): any; // deprecated, use intersectsBox() + isIntersectionSphere(s: any): any; // deprecated, use intersectsSphere() } export interface HSL { @@ -2714,6 +2859,7 @@ declare namespace THREE { set(color: Color): Color; set(color: number): Color; set(color: string): Color; + setScalar(scalar: number): Color; setHex(hex: number): Color; /** @@ -2804,165 +2950,164 @@ declare namespace THREE { toArray(array?: number[], offset?: number): number[]; } - export class ColorKeywords { - static aliceblue: number; - static antiquewhite: number; - static aqua: number; - static aquamarine: number; - static azure: number; - static beige: number; - static bisque: number; - static black: number; - static blanchedalmond: number; - static blue: number; - static blueviolet: number; - static brown: number; - static burlywood: number; - static cadetblue: number; - static chartreuse: number; - static chocolate: number; - static coral: number; - static cornflowerblue: number; - static cornsilk: number; - static crimson: number; - static cyan: number; - static darkblue: number; - static darkcyan: number; - static darkgoldenrod: number; - static darkgray: number; - static darkgreen: number; - static darkgrey: number; - static darkkhaki: number; - static darkmagenta: number; - static darkolivegreen: number; - static darkorange: number; - static darkorchid: number; - static darkred: number; - static darksalmon: number; - static darkseagreen: number; - static darkslateblue: number; - static darkslategray: number; - static darkslategrey: number; - static darkturquoise: number; - static darkviolet: number; - static deeppink: number; - static deepskyblue: number; - static dimgray: number; - static dimgrey: number; - static dodgerblue: number; - static firebrick: number; - static floralwhite: number; - static forestgreen: number; - static fuchsia: number; - static gainsboro: number; - static ghostwhite: number; - static gold: number; - static goldenrod: number; - static gray: number; - static green: number; - static greenyellow: number; - static grey: number; - static honeydew: number; - static hotpink: number; - static indianred: number; - static indigo: number; - static ivory: number; - static khaki: number; - static lavender: number; - static lavenderblush: number; - static lawngreen: number; - static lemonchiffon: number; - static lightblue: number; - static lightcoral: number; - static lightcyan: number; - static lightgoldenrodyellow: number; - static lightgray: number; - static lightgreen: number; - static lightgrey: number; - static lightpink: number; - static lightsalmon: number; - static lightseagreen: number; - static lightskyblue: number; - static lightslategray: number; - static lightslategrey: number; - static lightsteelblue: number; - static lightyellow: number; - static lime: number; - static limegreen: number; - static linen: number; - static magenta: number; - static maroon: number; - static mediumaquamarine: number; - static mediumblue: number; - static mediumorchid: number; - static mediumpurple: number; - static mediumseagreen: number; - static mediumslateblue: number; - static mediumspringgreen: number; - static mediumturquoise: number; - static mediumvioletred: number; - static midnightblue: number; - static mintcream: number; - static mistyrose: number; - static moccasin: number; - static navajowhite: number; - static navy: number; - static oldlace: number; - static olive: number; - static olivedrab: number; - static orange: number; - static orangered: number; - static orchid: number; - static palegoldenrod: number; - static palegreen: number; - static paleturquoise: number; - static palevioletred: number; - static papayawhip: number; - static peachpuff: number; - static peru: number; - static pink: number; - static plum: number; - static powderblue: number; - static purple: number; - static red: number; - static rosybrown: number; - static royalblue: number; - static saddlebrown: number; - static salmon: number; - static sandybrown: number; - static seagreen: number; - static seashell: number; - static sienna: number; - static silver: number; - static skyblue: number; - static slateblue: number; - static slategray: number; - static slategrey: number; - static snow: number; - static springgreen: number; - static steelblue: number; - static tan: number; - static teal: number; - static thistle: number; - static tomato: number; - static turquoise: number; - static violet: number; - static wheat: number; - static white: number; - static whitesmoke: number; - static yellow: number; - static yellowgreen: number; + export namespace ColorKeywords { + export const aliceblue: number; + export const antiquewhite: number; + export const aqua: number; + export const aquamarine: number; + export const azure: number; + export const beige: number; + export const bisque: number; + export const black: number; + export const blanchedalmond: number; + export const blue: number; + export const blueviolet: number; + export const brown: number; + export const burlywood: number; + export const cadetblue: number; + export const chartreuse: number; + export const chocolate: number; + export const coral: number; + export const cornflowerblue: number; + export const cornsilk: number; + export const crimson: number; + export const cyan: number; + export const darkblue: number; + export const darkcyan: number; + export const darkgoldenrod: number; + export const darkgray: number; + export const darkgreen: number; + export const darkgrey: number; + export const darkkhaki: number; + export const darkmagenta: number; + export const darkolivegreen: number; + export const darkorange: number; + export const darkorchid: number; + export const darkred: number; + export const darksalmon: number; + export const darkseagreen: number; + export const darkslateblue: number; + export const darkslategray: number; + export const darkslategrey: number; + export const darkturquoise: number; + export const darkviolet: number; + export const deeppink: number; + export const deepskyblue: number; + export const dimgray: number; + export const dimgrey: number; + export const dodgerblue: number; + export const firebrick: number; + export const floralwhite: number; + export const forestgreen: number; + export const fuchsia: number; + export const gainsboro: number; + export const ghostwhite: number; + export const gold: number; + export const goldenrod: number; + export const gray: number; + export const green: number; + export const greenyellow: number; + export const grey: number; + export const honeydew: number; + export const hotpink: number; + export const indianred: number; + export const indigo: number; + export const ivory: number; + export const khaki: number; + export const lavender: number; + export const lavenderblush: number; + export const lawngreen: number; + export const lemonchiffon: number; + export const lightblue: number; + export const lightcoral: number; + export const lightcyan: number; + export const lightgoldenrodyellow: number; + export const lightgray: number; + export const lightgreen: number; + export const lightgrey: number; + export const lightpink: number; + export const lightsalmon: number; + export const lightseagreen: number; + export const lightskyblue: number; + export const lightslategray: number; + export const lightslategrey: number; + export const lightsteelblue: number; + export const lightyellow: number; + export const lime: number; + export const limegreen: number; + export const linen: number; + export const magenta: number; + export const maroon: number; + export const mediumaquamarine: number; + export const mediumblue: number; + export const mediumorchid: number; + export const mediumpurple: number; + export const mediumseagreen: number; + export const mediumslateblue: number; + export const mediumspringgreen: number; + export const mediumturquoise: number; + export const mediumvioletred: number; + export const midnightblue: number; + export const mintcream: number; + export const mistyrose: number; + export const moccasin: number; + export const navajowhite: number; + export const navy: number; + export const oldlace: number; + export const olive: number; + export const olivedrab: number; + export const orange: number; + export const orangered: number; + export const orchid: number; + export const palegoldenrod: number; + export const palegreen: number; + export const paleturquoise: number; + export const palevioletred: number; + export const papayawhip: number; + export const peachpuff: number; + export const peru: number; + export const pink: number; + export const plum: number; + export const powderblue: number; + export const purple: number; + export const red: number; + export const rosybrown: number; + export const royalblue: number; + export const saddlebrown: number; + export const salmon: number; + export const sandybrown: number; + export const seagreen: number; + export const seashell: number; + export const sienna: number; + export const silver: number; + export const skyblue: number; + export const slateblue: number; + export const slategray: number; + export const slategrey: number; + export const snow: number; + export const springgreen: number; + export const steelblue: number; + export const tan: number; + export const teal: number; + export const thistle: number; + export const tomato: number; + export const turquoise: number; + export const violet: number; + export const wheat: number; + export const white: number; + export const whitesmoke: number; + export const yellow: number; + export const yellowgreen: number; } export class Euler { - static DefaultOrder: string; - constructor(x?: number, y?: number, z?: number, order?: string); - + x: number; y: number; z: number; order: string; + onChangeCallback: Function; set(x: number, y: number, z: number, order?: string): Euler; clone(): Euler; @@ -2975,7 +3120,10 @@ declare namespace THREE { fromArray(xyzo: any[]): Euler; toArray(array?: number[], offset?: number): number[]; toVector3(optionalResult?: Vector3): Vector3; - onChange: () => void; + onChange(callback: Function): void; + + static RotationOrders: string[]; + static DefautlOrder: string; } /** @@ -3001,6 +3149,7 @@ declare namespace THREE { export class Line3 { constructor(start?: Vector3, end?: Vector3); + start: Vector3; end: Vector3; @@ -3018,8 +3167,12 @@ declare namespace THREE { equals(line: Line3): boolean; } - interface Math { - generateUUID(): string; + /** + * + * @see src/math/Math.js + */ + export namespace Math { + export function generateUUID(): string; /** * Clamps the x to be between a and b. @@ -3028,8 +3181,8 @@ declare namespace THREE { * @param min Minimum value * @param max Maximum value. */ - clamp(value: number, min: number, max: number): number; - euclideanModulo( n: number, m: number ): number; + export function clamp(value: number, min: number, max: number): number; + export function euclideanModulo( n: number, m: number ): number; /** * Linear mapping of x from range [a1, a2] to range [b1, b2]. @@ -3040,50 +3193,44 @@ declare namespace THREE { * @param b1 Minimum value for range B. * @param b2 Maximum value for range B. */ - mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number; + export function mapLinear(x: number, a1: number, a2: number, b1: number, b2: number): number; - smoothstep(x: number, min: number, max: number): number; + export function smoothstep(x: number, min: number, max: number): number; - smootherstep(x: number, min: number, max: number): number; + export function smootherstep(x: number, min: number, max: number): number; /** * Random float from 0 to 1 with 16 bits of randomness. * Standard Math.random() creates repetitive patterns when applied over larger space. */ - random16(): number; + export function random16(): number; // deprecated, use Math.random() /** * Random integer from low to high interval. */ - randInt(low: number, high: number): number; + export function randInt(low: number, high: number): number; /** * Random float from low to high interval. */ - randFloat(low: number, high: number): number; + export function randFloat(low: number, high: number): number; /** * Random float from - range / 2 to range / 2 interval. */ - randFloatSpread(range: number): number; + export function randFloatSpread(range: number): number; - degToRad(degrees: number): number; + export function degToRad(degrees: number): number; - radToDeg(radians: number): number; + export function radToDeg(radians: number): number; - isPowerOfTwo(value: number): boolean; + export function isPowerOfTwo(value: number): boolean; - nearestPowerOfTwo(value: number): number; + export function nearestPowerOfTwo(value: number): number; - nextPowerOfTwo(value: number): number; + export function nextPowerOfTwo(value: number): number; } - /** - * - * @see src/math/Math.js - */ - export var Math: Math; - /** * ( interface Matrix<T> ) */ @@ -3135,11 +3282,6 @@ declare namespace THREE { */ constructor(); - /** - * Initialises the matrix with the supplied n11..n33 values. - */ - constructor(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number); - /** * Float32Array with matrix values. */ @@ -3149,12 +3291,13 @@ declare namespace THREE { identity(): Matrix3; clone(): Matrix3; copy(m: Matrix3): Matrix3; + multiplyVector3Array(a: any): any; // deprecated, use applyToVector3Array() applyToVector3Array(array: number[], offset?: number, length?: number): number[]; - applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; + applyToBuffer(buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; multiplyScalar(s: number): Matrix3; determinant(): number; - getInverse(matrix: Matrix3, throwOnInvertible?: boolean): Matrix3; - getInverse(matrix: Matrix4, throwOnInvertible?: boolean): Matrix3; + getInverse(matrix: Matrix3, throwOnDegenerate?: boolean): Matrix3; + getInverse(matrix: Matrix4, throwOnDegenerate?: boolean): Matrix3; /** * Transposes this matrix in place. @@ -3170,6 +3313,7 @@ declare namespace THREE { fromArray(array: number[]): Matrix3; toArray(): number[]; + multiplyVector3(vector: Vector3): any; // deprecated, use vector.applyMatrix3( matrix ) } /** @@ -3191,10 +3335,7 @@ declare namespace THREE { * m.multiply( m3 ); */ export class Matrix4 implements Matrix { - /** - * Initialises the matrix with the supplied n11..n44 values. - */ - constructor(n11?: number, n12?: number, n13?: number, n14?: number, n21?: number, n22?: number, n23?: number, n24?: number, n31?: number, n32?: number, n33?: number, n34?: number, n41?: number, n42?: number, n43?: number, n44?: number); + constructor(); /** * Float32Array with matrix values. @@ -3212,6 +3353,7 @@ declare namespace THREE { identity(): Matrix4; clone(): Matrix4; copy(m: Matrix4): Matrix4; + extractPosition(m: Matrix4): Matrix4; // deprecated, use copyPosition() copyPosition(m: Matrix4): Matrix4; extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; @@ -3221,6 +3363,7 @@ declare namespace THREE { */ extractRotation(m: Matrix4): Matrix4; makeRotationFromEuler(euler: Euler): Matrix4; + setRotationFromQuaternion(q: Quaternion): Matrix4; // deprecated, use makeRotationFromQuaternion() makeRotationFromQuaternion(q: Quaternion): Matrix4; /** * Constructs a rotation matrix, looking from eye towards center with defined up vector. @@ -3247,6 +3390,7 @@ declare namespace THREE { * Multiplies this matrix by s. */ multiplyScalar(s: number): Matrix4; + multiplyVector3Array(array: number[]): number[]; // deprecated, use applyToVector3Array() applyToVector3Array(array: number[], offset?: number, length?: number): number[]; applyToBuffer( buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; /** @@ -3268,7 +3412,8 @@ declare namespace THREE { /** * Sets the position component for this matrix from vector v. */ - setPosition(v: Vector3): Vector3; + setPosition(v: Vector3): Matrix4; + /** * Sets this matrix to the inverse of matrix m. @@ -3350,6 +3495,12 @@ declare namespace THREE { equals( matrix: Matrix4 ): boolean; fromArray(array: number[]): Matrix4; toArray(): number[]; + + getPosition(): any; // deprecated, use Vector3.setFromMatrixPosition( matrix ) + multiplyVector3(v: any): any; // deprecated, use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) + multiplyVector4(v: any): any; // deprecated, use vector.applyMatrix4( matrix ) + rotateAxis(v: any): void; // deprecated, use Vector3.transformDirection( matrix ) + crossVector(v: any): void; // deprecated, use vector.applyMatrix( matrix ) } export class Plane { @@ -3370,12 +3521,15 @@ declare namespace THREE { distanceToSphere(sphere: Sphere): number; projectPoint(point: Vector3, optionalTarget?: Vector3): Vector3; orthoPoint(point: Vector3, optionalTarget?: Vector3): Vector3; - isIntersectionLine(line: Line3): boolean; intersectLine(line: Line3, optionalTarget?: Vector3): Vector3; + intersectsLine(line: Line3): boolean; + intersectsBox(box: Box3): boolean; coplanarPoint(optionalTarget?: boolean): Vector3; applyMatrix4(matrix: Matrix4, optionalNormalMatrix?: Matrix3): Plane; translate(offset: Vector3): Plane; equals(plane: Plane): boolean; + + isIntersectionLine(l: any): any; // deprecated, use instersectsLine() } /** @@ -3463,10 +3617,8 @@ declare namespace THREE { */ multiplyQuaternions(a: Quaternion, b: Quaternion): Quaternion; - /** - * Deprecated. Use Vector3.applyQuaternion instead - */ - multiplyVector3(vector: Vector3): Vector3; + multiplyVector3(v: any): any; // deprecated, use vector.applyQuaternion( quaternion ) + slerp(qb: Quaternion, t: number): Quaternion; equals(v: Quaternion): boolean; fromArray(n: number[]): Quaternion; @@ -3475,12 +3627,15 @@ declare namespace THREE { fromArray(xyzw: number[], offset?: number): Quaternion; toArray(xyzw?: number[], offset?: number): number[]; - onChange: () => void; + onChange(callback: Function): Quaternion; + onChangeCallback: Function; /** * Adapted from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/. */ static slerp(qa: Quaternion, qb: Quaternion, qm: Quaternion, t: number): Quaternion; + + static slerpFlat(dst: number[], dstOffset: number, src0: number[], srcOffset: number, src1: number[], stcOffset1: number, t: number): Quaternion; } export class Ray { @@ -3493,21 +3648,26 @@ declare namespace THREE { clone(): Ray; copy(ray: Ray): Ray; at(t: number, optionalTarget?: Vector3): Vector3; + lookAt(v: Vector3): Vector3; recast(t: number): Ray; closestPointToPoint(point: Vector3, optionalTarget?: Vector3): Vector3; distanceToPoint(point: Vector3): number; distanceSqToPoint(point: Vector3): number; distanceSqToSegment(v0: Vector3, v1: Vector3, optionalPointOnRay?: Vector3, optionalPointOnSegment?: Vector3): number; - isIntersectionSphere(sphere: Sphere): boolean; intersectSphere(sphere: Sphere, optionalTarget?: Vector3): Vector3; - isIntersectionPlane(plane: Plane): boolean; + intersectsSphere(sphere: Sphere): boolean; distanceToPlane(plane: Plane): number; intersectPlane(plane: Plane, optionalTarget?: Vector3): Vector3; - isIntersectionBox(box: Box3): boolean; + intersectsPlane(plane: Plane): boolean; intersectBox(box: Box3, optionalTarget?: Vector3): Vector3; + intersectsBox(box: Box3): boolean; intersectTriangle(a: Vector3, b: Vector3, c: Vector3, backfaceCulling: boolean, optionalTarget?: Vector3): Vector3; applyMatrix4(matrix4: Matrix4): Ray; equals(ray: Ray): boolean; + + isIntersectionSphere(s: any): any; // deprecated, use intersectsSphere() + isIntersectionPlane(p: any): any; // deprecated, use intersectsPlane() + isIntersectionBox(b: any): any; // deprecated, use intersectsBox() } export class Sphere { @@ -3524,6 +3684,8 @@ declare namespace THREE { containsPoint(point: Vector3): boolean; distanceToPoint(point: Vector3): number; intersectsSphere(sphere: Sphere): boolean; + intersectsBox(box: Box3): boolean; + intersectsPlane(plane: Plane): boolean; clampPoint(point: Vector3, optionalTarget?: Vector3): Vector3; getBoundingBox(optionalTarget?: Box3): Box3; applyMatrix4(matrix: Matrix4): Sphere; @@ -3608,7 +3770,6 @@ declare namespace THREE { static containsPoint(point: Vector3, a: Vector3, b: Vector3, c: Vector3): boolean; } - /** * ( interface Vector<T> ) * @@ -3730,7 +3891,6 @@ declare namespace THREE { x: number; y: number; - width: number; height: number; @@ -3739,6 +3899,8 @@ declare namespace THREE { */ set(x: number, y: number): Vector2; + setScalar(scalar: number): Vector2; + /** * Sets X component of this vector. */ @@ -3838,6 +4000,11 @@ declare namespace THREE { */ normalize(): Vector2; + /** + * computes the angle in radians with respect to the positive x-axis + */ + angle(): number; + /** * Computes distance of this vector to v. */ @@ -3885,7 +4052,6 @@ declare namespace THREE { * ( class Vector3 implements Vector ) */ export class Vector3 implements Vector { - constructor(x?: number, y?: number, z?: number); x: number; @@ -3897,6 +4063,11 @@ declare namespace THREE { */ set(x: number, y: number, z: number): Vector3; + /** + * Sets all values of this vector. + */ + setScalar(scalar: number): Vector3; + /** * Sets x value of this vector. */ @@ -3934,7 +4105,6 @@ declare namespace THREE { * Sets this vector to a + b. */ addVectors(a: Vector3, b: Vector3): Vector3; - addScaledVector( v: Vector3, s: number ): Vector3; /** * Subtracts v from this vector. @@ -4043,8 +4213,11 @@ declare namespace THREE { */ distanceToSquared(v: Vector3): number; + getPositionFromMatrix(m: Matrix4): Vector3; // deprecated, use setFromMatrixPosition() setFromMatrixPosition(m: Matrix4): Vector3; + getScaleFromMatrix(m: Matrix4): Vector3; // deprecated, use setFromMatrixScale() setFromMatrixScale(m: Matrix4): Vector3; + getColumnFromMatrixColumn(index: number, matrix: Matrix4): Vector3; // deprecated, use setFromMatrixColumn() setFromMatrixColumn(index: number, matrix: Matrix4): Vector3; /** @@ -4066,6 +4239,7 @@ declare namespace THREE { */ export class Vector4 implements Vector { constructor(x?: number, y?: number, z?: number, w?: number); + x: number; y: number; z: number; @@ -4076,6 +4250,11 @@ declare namespace THREE { */ set(x: number, y: number, z: number, w: number): Vector4; + /** + * Sets all values of this vector. + */ + setScalar(scalar: number): Vector4; + /** * Sets X component of this vector. */ @@ -4152,7 +4331,7 @@ declare namespace THREE { * http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm * @param m assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled) */ - setAxisAngleFromRotationMatrix(m: Matrix4): Vector4; + setAxisAngleFromRotationMatrix(m: Matrix3): Vector4; min(v: Vector4): Vector4; max(v: Vector4): Vector4; @@ -4212,6 +4391,41 @@ declare namespace THREE { fromAttribute( attribute: BufferAttribute, index: number, offset?: number): Vector4; } + export abstract class Interpolant { + constructor(parameterPositions: any, samplesValues: any, sampleSize: number, resultBuffer?: any); + + parameterPositions: any; + samplesValues: any; + valueSize: number; + resultBuffer: any; + + evaluate(time: number): any; + } + + export class CubicInterpolant extends Interpolant { + constructor(parameterPositions: any, samplesValues: any, sampleSize: number, resultBuffer?: any); + + interpolate_(i1: number, t0: number, t: number, t1: number): any; + } + + export class DiscreteInterpolant extends Interpolant { + constructor(parameterPositions: any, samplesValues: any, sampleSize: number, resultBuffer?: any); + + interpolate_(i1: number, t0: number, t: number, t1: number): any; + } + + export class LinearInterpolant extends Interpolant { + constructor(parameterPositions: any, samplesValues: any, sampleSize: number, resultBuffer?: any); + + interpolate_(i1: number, t0: number, t: number, t1: number): any; + } + + export class QuaternionLinearInterpolant extends Interpolant { + constructor(parameterPositions: any, samplesValues: any, sampleSize: number, resultBuffer?: any); + + interpolate_(i1: number, t0: number, t: number, t1: number): any; + } + // Objects ////////////////////////////////////////////////////////////////////////////////// export class Bone extends Object3D { @@ -4231,6 +4445,7 @@ declare namespace THREE { constructor(); levels: any[]; + objects: any[]; // deprecated, use .levels addLevel(object: Object3D, distance?: number): void; getObjectForDistance(distance: number): Object3D; @@ -4263,11 +4478,9 @@ declare namespace THREE { positionScreen: Vector3; customUpdateCallback: (object: LensFlare) => void; + add(object: Object3D): void; add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; - add(obj: Object3D): void; - updateLensFlares(): void; - clone(): LensFlare; copy(source: LensFlare): LensFlare; } @@ -4298,9 +4511,9 @@ declare namespace THREE { copy(source: LineSegments): LineSegments; } - enum LineMode{} - var LineStrip: LineMode; - var LinePieces: LineMode; + enum LineMode {} + var LineStrip: LineMode; // deprecated + var LinePieces: LineMode; // deprecated export class Mesh extends Object3D { constructor(geometry?: Geometry, material?: Material); @@ -4308,7 +4521,9 @@ declare namespace THREE { geometry: Geometry|BufferGeometry; material: Material; + drawMode: TrianglesDrawModes; + setDrawMode(drawMode: TrianglesDrawModes): void; updateMorphTargets(): void; getMorphTargetIndexByName(name: string): number; raycast(raycaster: Raycaster, intersects: any): void; @@ -4338,7 +4553,7 @@ declare namespace THREE { geometry: Geometry; /** - * An instance of Material, defining the object's appearance. Default is a ParticleBasicMaterial with randomised colour. + * An instance of Material, defining the object's appearance. Default is a PointsMaterial with randomised colour. */ material: Material; @@ -4347,6 +4562,9 @@ declare namespace THREE { copy(source: Points): Points; } + export class PointCloud extends Points {} // deprecated, use Points + export class ParticleSystem extends Points {} // deprecated, use Points + export class Skeleton { constructor(bones: Bone[], boneInverses?: Matrix4[], useVertexTexture?: boolean); @@ -4363,13 +4581,12 @@ declare namespace THREE { pose(): void; update(): void; clone(): Skeleton; - } export class SkinnedMesh extends Mesh { constructor(geometry?: Geometry|BufferGeometry, material?: MeshBasicMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry|BufferGeometry, material?: MeshDepthMaterial, useVertexTexture?: boolean); - constructor(geometry?: Geometry|BufferGeometry, material?: MeshFaceMaterial, useVertexTexture?: boolean); + constructor(geometry?: Geometry|BufferGeometry, material?: MultiMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry|BufferGeometry, material?: MeshLambertMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry|BufferGeometry, material?: MeshNormalMaterial, useVertexTexture?: boolean); constructor(geometry?: Geometry|BufferGeometry, material?: MeshPhongMaterial, useVertexTexture?: boolean); @@ -4378,15 +4595,14 @@ declare namespace THREE { bindMode: string; bindMatrix: Matrix4; bindMatrixInverse: Matrix4; + skeleton: Skeleton; bind( skeleton: Skeleton, bindMatrix?: Matrix4 ): void; pose(): void; normalizeSkinWeights(): void; updateMatrixWorld(force?: boolean): void; clone(): SkinnedMesh; - copy(source?: SkinnedMesh): SkinnedMesh; - - skeleton: Skeleton; + copy(source: SkinnedMesh): SkinnedMesh; } export class Sprite extends Object3D { @@ -4397,9 +4613,11 @@ declare namespace THREE { raycast(raycaster: Raycaster, intersects: any): void; clone(): Sprite; - copy(source?: Sprite): Sprite; + copy(source: Sprite): Sprite; } + export class Particle extends Sprite {} // deprecated, use Sprite + // Renderers ////////////////////////////////////////////////////////////////////////////////// @@ -4514,7 +4732,7 @@ declare namespace THREE { extensions: WebGLExtensions; - gammaFactor: number; + gammaFactor: number; // deprecated /** * Default is false. @@ -4526,22 +4744,6 @@ declare namespace THREE { */ gammaOutput: boolean; - /** - * Default is false. - */ - shadowMapEnabled: boolean; - - /** - * Defines shadow map type (unfiltered, percentage close filtering, percentage close filtering with bilinear filtering in shader) - * Options are THREE.BasicShadowMap, THREE.PCFShadowMap, THREE.PCFSoftShadowMap. Default is THREE.PCFShadowMap. - */ - shadowMapType: ShadowMapType; - - /** - * Default is true - */ - shadowMapCullFace: CullFace; - /** * Default is false. */ @@ -4567,7 +4769,6 @@ declare namespace THREE { */ info: { memory: { - programs: number; geometries: number; textures: number; }; @@ -4577,32 +4778,32 @@ declare namespace THREE { faces: number; points: number; }; + programs: number; }; - shadowMap: WebGLShadowMapInstance; + shadowMap: WebGLShadowMap; + shadowMapType: ShadowMapType; // deprecated, use shadowMap.type + shadowMapEnabled: boolean; // deprecated, use shadowMap.enabled + shadowMapCullFace: CullFace; // deprecated, use shadowMap.cullFace + + pixelRation: number; + + capabilities: WebGLCapabilities; + properties: WebGLProperties; + state: WebGLState; /** * Return the WebGL context. */ getContext(): WebGLRenderingContext; - + getContextAttributes(): any; forceContextLoss(): void; - capabilities: WebGLCapabilities; - - /** Deprecated, use capabilities instead */ - supportsVertexTextures(): boolean; - supportsFloatTextures(): boolean; - supportsStandardDerivatives(): boolean; - supportsCompressedTextureS3TC(): boolean; - supportsCompressedTexturePVRTC(): boolean; - supportsBlendMinMax(): boolean; - getPrecision(): string; - getMaxAnisotropy(): number; + getPrecision(): string; getPixelRatio(): number; setPixelRatio(value: number): void; - + getSize(): { width: number; height: number; }; /** @@ -4623,37 +4824,26 @@ declare namespace THREE { /** * Enable the scissor test. When this is enabled, only the pixels within the defined scissor area will be affected by further renderer actions. */ - enableScissorTest(enable: boolean): void; - - /** - * Sets the clear color, using color for the color and alpha for the opacity. - */ - setClearColor(color: Color, alpha?: number): void; - setClearColor(color: string, alpha?: number): void; - setClearColor(color: number, alpha?: number): void; - - setClearAlpha(alpha: number): void; - - /** - * Sets the clear color, using hex for the color and alpha for the opacity. - * - * @example - * // Creates a renderer with black background - * var renderer = new THREE.WebGLRenderer(); - * renderer.setSize(200, 100); - * renderer.setClearColorHex(0x000000, 1); - */ - setClearColorHex(hex: number, alpha: number): void; + setScissorTest(enable: boolean): void; /** * Returns a THREE.Color instance with the current clear color. */ getClearColor(): Color; + /** + * Sets the clear color, using color for the color and alpha for the opacity. + */ + setClearColor(color: Color, alpha?: number): void; + setClearColor(color: string, alpha?: number): void; + setClearColor(color: number, alpha?: number): void; + /** * Returns a float with the current clear alpha. Ranges from 0 to 1. */ getClearAlpha(): number; + + setClearAlpha(alpha: number): void; /** * Tells the renderer to clear its color, depth or stencil drawing buffer(s). @@ -4674,13 +4864,9 @@ declare namespace THREE { * @param scene an instance of Scene * @param camera — an instance of Camera */ - updateShadowMap(scene: Scene, camera: Camera): void; - renderBufferImmediate(object: Object3D, program: Object, material: Material): void; - renderBufferDirect(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; - - renderBuffer(camera: Camera, lights: Light[], fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; + renderBufferDirect(camera: Camera, fog: Fog, material: Material, geometryGroup: any, object: Object3D): void; /** * Render a scene using a camera. @@ -4688,7 +4874,6 @@ declare namespace THREE { * If forceClear is true, the canvas will be cleared before rendering, even if the renderer's autoClear property is false. */ render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void; - renderImmediateObject(camera: Camera, lights: Light[], fog: Fog, material: Material, object: Object3D): void; /** * Used for setting the gl frontFace, cullFace states in the GPU, thus enabling/disabling face culling when rendering. @@ -4697,14 +4882,19 @@ declare namespace THREE { * @param frontFace "ccw" or "cw */ setFaceCulling(cullFace?: CullFace, frontFace?: FrontFaceDirection): void; - setMaterialFaces(material: Material): void; - setDepthTest(depthTest: boolean): void; - setDepthWrite(depthWrite: boolean): void; - setBlending(blending: Blending, blendEquation: BlendingEquation, blendSrc: BlendingSrcFactor, blendDst: BlendingDstFactor): void; - uploadTexture(texture: Texture): void; setTexture(texture: Texture, slot: number): void; setRenderTarget(renderTarget: RenderTarget): void; readRenderTargetPixels( renderTarget: RenderTarget, x: number, y: number, width: number, height: number, buffer: any ): void; + + supportsFloatTextures(): any; // deprecated + supportsHalfFloatTextures(): any; // deprecated + supportsStandardDerivatives(): any; // deprecated + supportsCompressedTextureS3TC(): any; // deprecated + supportsCompressedTexturePVRTC(): any; // deprecated + supportsBlendMinMax(): any; // deprecated + supportsVertexTextures(): any; // deprecated + supportsInstancedArrays(): any; // deprecated + enableScissorTest(boolean: any): any; // deprecated } export interface RenderTarget { @@ -4715,9 +4905,9 @@ declare namespace THREE { wrapT?: Wrapping; magFilter?: TextureFilter; minFilter?: TextureFilter; - anisotropy?: number; // 1; format?: number; // RGBAFormat; type?: TextureDataType; // UnsignedByteType; + anisotropy?: number; // 1; depthBuffer?: boolean; // true; stencilBuffer?: boolean; // true; } @@ -4728,26 +4918,29 @@ declare namespace THREE { uuid: string; width: number; height: number; - wrapS: Wrapping; - wrapT: Wrapping; - magFilter: TextureFilter; - minFilter: TextureFilter; - anisotropy: number; - offset: Vector2; - repeat: Vector2; - format: number; - type: number; + scissor: Vector4; + scissorTest: boolean; + viewpport: Vector4; + texture: Texture; depthBuffer: boolean; stencilBuffer: boolean; - generateMipmaps: boolean; shareDepthFrom: any; + wrapS: any; // deprecated, use texture.wrapS + wrapT: any; // deprecated, use texture.wrapT + magFilter: any; // deprecated, use texture.magFilter + minFilter: any; // deprecated, use texture.minFilter + anisotropy: any; // deprecated, use texture.anisotropy + offset: any; // deprecated, use texture.offset + repeat: any; // deprecated, use texture.repeat + format: any; // deprecated, use texture.format + type: any; // deprecated, use texture.type + generateMipmaps: any; // deprecated, use texture.generateMipmaps setSize(width: number, height: number): void; clone(): WebGLRenderTarget; copy(source: WebGLRenderTarget): WebGLRenderTarget; dispose(): void; - // EventDispatcher mixins addEventListener(type: string, listener: (event: any) => void ): void; hasEventListener(type: string, listener: (event: any) => void): void; @@ -4762,26 +4955,27 @@ declare namespace THREE { } // Renderers / Shaders ///////////////////////////////////////////////////////////////////// - export interface ShaderChunk { + export let ShaderChunk: { [name: string]: string; - common: string; - alphamap_fragment: string; alphamap_pars_fragment: string; alphatest_fragment: string; + ambient_pars: string; aomap_fragment: string; aomap_pars_fragment: string; begin_vertex: string; beginnormal_vertex: string; + bsdfs: string; bumpmap_pars_fragment: string; color_fragment: string; color_pars_fragment: string; color_pars_vertex: string; color_vertex: string; + common: string; defaultnormal_vertex: string; - displacementmap_pars_vertex: string; displacementmap_vertex: string; + displacementmap_pars_vertex: string; emissivemap_fragment: string; emissivemap_pars_fragment: string; envmap_fragment: string; @@ -4790,15 +4984,17 @@ declare namespace THREE { envmap_vertex: string; fog_fragment: string; fog_pars_fragment: string; - hemilight_fragment: string; lightmap_fragment: string; lightmap_pars_fragment: string; - lights_lambert_pars_vertex: string; lights_lambert_vertex: string; + lights_pars: string; lights_phong_fragment: string; lights_phong_pars_fragment: string; lights_phong_pars_vertex: string; lights_phong_vertex: string; + lights_standard_fragment: string; + lights_standard_pars_fragment: string; + lights_template: string; linear_to_gamma_fragment: string; logdepthbuf_fragment: string; logdepthbuf_pars_fragment: string; @@ -4808,16 +5004,20 @@ declare namespace THREE { map_pars_fragment: string; map_particle_fragment: string; map_particle_pars_fragment: string; + metalnessmap_fragment: string; + metalnessmap_pars_fragment: string; morphnormal_vertex: string; morphtarget_pars_vertex: string; morphtarget_vertex: string; - normal_phong_fragment: string; + normal_fragment: string; normalmap_pars_fragment: string; project_vertex: string; - shadowmap_fragment: string; + roughtnessmap_fragment: string; + roughtnessmap_pars_fragment: string; shadowmap_pars_fragment: string; shadowmap_pars_vertex: string; shadowmap_vertex: string; + shadowmask_pars_fragment: string; skinbase_vertex: string; skinning_pars_vertex: string; skinning_vertex: string; @@ -4833,62 +5033,134 @@ declare namespace THREE { worldpos_vertex: string; } - export var ShaderChunk: ShaderChunk; - export interface Shader { uniforms: any; vertexShader: string; fragmentShader: string; } - export var ShaderLib: { + export let ShaderLib: { [name: string]: Shader; basic: Shader; lambert: Shader; phong: Shader; - particle_basic: Shader; + standard: Shader; + points: Shader; dashed: Shader; depth: Shader; normal: Shader; - normalmap: Shader; cube: Shader; equirect: Shader; depthRGBA: Shader; + distanceRGBA: Shader; }; - export var UniformsLib: { - common: any; - aomap: any; - lightmap: any; - emissivemap: any; - bumpmap: any; - normalmap: any; - displacementmap: any; - fog: any; - lights: any; - points: any; - shadowmap: any; - }; - - export var UniformsUtils: { - merge(uniforms: any[]): any; - clone(uniforms_src: any): any; - }; - - // Renderers / WebGL ///////////////////////////////////////////////////////////////////// - export class WebGLBufferRenderer{ - constructor(_gl: any, extensions: any, _infoRender: any); // WebGLRenderingContext - - setMode( value: any ): void; - render( start: any, count: any ): void; - renderInstances( geometry: any ): void; + export interface IUniform { + type: string; + value: any; } - export class WebGLCapabilities{ - constructor(gl: any, extensions: any, parameters: any); // WebGLRenderingContext + export let UniformsLib: { + common: { + diffuse: IUniform; + opacity: IUniform; + map: IUniform; + offsetRepeat: IUniform; + specularMap: IUniform; + alphaMap: IUniform; + envMap: IUniform; + flipEnvMap: IUniform; + reflectivity: IUniform; + refractionRation: IUniform; + }; + aomap: { + aoMap: IUniform; + aoMapIntensity: IUniform; + }; + lightmap: { + lightMap: IUniform; + lightMapIntensity: IUniform; + }; + emissivemap: { emissiveMap: IUniform }; + bumpmap: { + bumpMap: IUniform; + bumpScale: IUniform; + }; + normalmap: { + normalMap: IUniform; + normalScale: IUniform; + }; + displacementmap: { + displacementMap: IUniform; + displacementScale: IUniform; + displacementBias: IUniform; + }; + roughtnessmap: { roughtnessMap: IUniform }; + metalnessmap: { metalnessMap: IUniform }; + fog: { + fogDensity: IUniform; + fogNear: IUniform; + fogFar: IUniform; + fogColor: IUniform; + }; + ambient: { ambientLightColor: IUniform }; + lights: { + directionalLights: any; + directionalShadowMap: IUniform; + directionalShadowMatrix: IUniform; + spotLights: any; + spotShadowMap: IUniform; + spotShadowMatrix: IUniform; + pointLights: any; + pointShadowMap: IUniform; + pointShadowMatrix: IUniform; + hemisphereLigtts: any; + }; + points: { + diffuse: IUniform; + opacity: IUniform; + size: IUniform; + scale: IUniform; + map: IUniform; + offsetRepeat: IUniform; + }; + }; + + export namespace UniformsUtils { + export function merge(uniforms: any[]): any; + export function clone(uniforms_src: any): any; + } + + export class Uniform { + constructor(type: string, value: string); + + type: string; + value: string; + dynamic: boolean; + onUpdateCallback: Function; + + onUpdate(callback: Function): Uniform; + } + + // Renderers / WebGL ///////////////////////////////////////////////////////////////////// + export class WebGLBufferRenderer { + constructor(_gl: any, extensions: any, _infoRender: any); // WebGLRenderingContext + + setMode(value: any): void; + render(start: any, count: any): void; + renderInstances(geometry: any): void; + } + + export interface WebGLCapabilitiesParameters { + precision?: any; + logarithmicDepthBuffer?: any; + } + + export class WebGLCapabilities { + constructor(gl: any, extensions: any, parameters: WebGLCapabilitiesParameters); // WebGLRenderingContext - getMaxPrecision: any; precision: any; + logarithmicDepthBuffer: any; maxTextures: any; maxVertexTextures: any; maxTextureSize: any; @@ -4900,154 +5172,168 @@ declare namespace THREE { vertexTextures: any; floatFragmentTextures: any; floatVertexTextures: any; + + getMaxPrecision(precision: any): any; } - export class WebGLExtensions{ + export class WebGLExtensions { constructor(gl: any); // WebGLRenderingContext get(name: string): any; } - interface WebGLGeometriesInstance { - get( object: any ): any; - } - interface WebGLGeometriesStatic{ - new (gl: any, properties: any, info: any): WebGLGeometriesInstance; - } - export var WebGLGeometries: WebGLGeometriesStatic; + export class WebGLGeometries { + constructor(_gl: any, extensions: any, _infoRender: any); - - interface WebGLIndexedBufferRendererInstance { - setMode( value: any ): void; - setIndex( index: any ): void; - render( start: any, count: any ): void; - renderInstances( geometry: any ): void; + get(object: any): any; } - interface WebGLIndexedBufferRendererStatic{ - new (gl: any, properties: any, info: any): WebGLIndexedBufferRendererInstance; + + export class WebGLLights { + constructor(gl: any, properties: any, info: any); + + get(light: any): any; } - export var WebGLIndexedBufferRenderer: WebGLIndexedBufferRendererStatic; + export class WebGLIndexedBufferRenderer { + constructor(gl: any, properties: any, info: any); - interface WebGLObjectsInstance { - getAttributeBuffer( attribute: any ): any; + setMode(value: any): void; + setIndex(index: any): void; + render(start: any, count: number): void; + renderInstances(geometry: any, start: any, count: number): void; + } + + export class WebGLObjects { + constructor(gl: any, properties: any, info: any); + + getAttributeBuffer(attribute: any): any; getWireframeAttribute(geometry: any): any; update(object: any): void; } - interface WebGLObjectsStatic{ - new (gl: any, properties: any, info: any): WebGLObjectsInstance; - } - export var WebGLObjects: WebGLObjectsStatic; - export class WebGLProgram{ + export class WebGLProgram { constructor(renderer: WebGLRenderer, code: string, material: ShaderMaterial, parameters: WebGLRendererParameters); - - getUniforms(): any; - getAttributes(): any; - - /** Deprecated, use getUniforms */ - uniforms: any; - /** Deprecated, use getAttributes */ - attributes: any; - + id: number; code: string; usedTimes: number; program: any; vertexShader: WebGLShader; fragmentShader: WebGLShader; + uniforms: any; // deprecated, use getUniforms() + attributes: any; // deprecated, use getAttributes() + + getUniforms(): any; + getAttributes(): any; + destroy(): void; } - interface WebGLProgramsInstance { - getParameters( material: any, lights: any, fog: any, object: any ): any[]; - getProgramCode( material: any, parameters: any ): any; - acquireProgram( material: any, parameters: any, code: any ): any; - releaseProgram( program: any ): void; + export class WebGLPrograms { + constructor(renderer: WebGLRenderer, capabilities: any); + + programs: any[]; + + getParameters(material: ShaderMaterial, lights: any, fog: any, object: any): any[]; + getProgramCode(material: ShaderMaterial, parameters: any): string; + acquireProgram(material: ShaderMaterial, parameters: any, code: string): WebGLProgram; + releaseProgram(program: WebGLProgram): void; } - interface WebGLProgramsStatic{ - new (renderer: WebGLRenderer, capabilities: any): WebGLProgramsInstance; - } - export var WebGLPrograms: WebGLProgramsStatic; + + export class WebGLProperties { + constructor(); - interface WebGLPropertiesInstance { get(object: any): any; delete(object: any): void; clear(): void; } - interface WebGLPropertiesStatic{ - new (): WebGLPropertiesInstance; - } - export var WebGLProperties: WebGLPropertiesStatic; - export class WebGLShader{ + export class WebGLShader { constructor(gl: any, type: string, string: string); } - interface WebGLShadowMapInstance{ + export class WebGLShadowMap { + constructor(_renderer: Renderer, _lights: any[], _objects: any[]); + enabled: boolean; autoUpdate: boolean; needsUpdate: boolean; type: ShadowMapType; cullFace: CullFace; - render( scene: Scene ): void; + render(scene: Scene, camera: Camera): void; } - interface WebGLShadowMapStatic{ - new ( _renderer: Renderer, _lights: any[], _objects: any[] ): WebGLStateInstance; - } - export var WebGLShadowMap: WebGLShadowMapStatic; + + export class WebGLState { + constructor(gl: any, extensions: any, paramThreeToGL: Function); - interface WebGLStateInstance{ init(): void; initAttributes(): void; enableAttribute(attribute: string): void; - enableAttributeAndDivisor( attribute: string, meshPerAttribute: any, extension: any ): void; + enableAttributeAndDivisor(attribute: string, meshPerAttribute: any, extension: any): void; disableUnusedAttributes(): void; - enable( id: string ): void; - disable( id: string ): void; - getCompressedTextureFormats(): any; - setBlending( blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number ): void; - setDepthFunc( func: Function): void; - setDepthTest( depthTest: number ): void; - setDepthWrite( depthWrite: number ): void; - setColorWrite( colorWrite: number ): void; - setFlipSided( flipSided: number ): void; - setLineWidth( width: number ): void; + enable(id: string): void; + disable(id: string): void; + getCompressedTextureFormats(): any[]; + setBlending(blending: number, blendEquation: number, blendSrc: number, blendDst: number, blendEquationAlpha: number, blendSrcAlpha: number, blendDstAlpha: number): void; + setDepthFunc(func: Function): void; + setDepthTest(depthTest: number): void; + setDepthWrite(depthWrite: number): void; + setColorWrite(colorWrite: number): void; + setStencilFunc(stencilFunc: Function, stencilRef: any, stencilMask: any): void; + setStencilOp(stencilFail: any, stencilZFail: any, stencilZPass: any): void; + setStencilTest(stencilTest: boolean): void; + setStencilWrite(stencilWrite: any): void; + setFlipSided(flipSided: number): void; + setLineWidth(width: number): void; setPolygonOffset(polygonoffset: number, factor: number, units: number): void; - setScissorTest( scissorTest: boolean ): void; - activeTexture( webglSlot: any ): void; - bindTexture( webglType: any, webglTexture: any ): void; + setScissorTest(scissorTest: boolean): void; + getScissorTest(): boolean; + activeTexture(webglSlot: any): void; + bindTexture(webglType: any, webglTexture: any): void; compressedTexImage2D(): void; texImage2D(): void; + clearColor(r: number, g: number, b: number, a: number): void; + clearDepth(depth: number): void; + clearStencil(stencil: any): void; + scissor(scissor: any): void; + viewport(viewport: any): void; reset(): void; } - interface WebGLStateStatic{ - new ( gl: any, extensions: any, paramThreeToGL: Function ): WebGLStateInstance; - } - export var WebGLState: WebGLStateStatic; - // Renderers / WebGL / Plugins ///////////////////////////////////////////////////////////////////// - export interface RendererPlugin { - init(renderer: WebGLRenderer): void; - render(scene: Scene, camera: Camera, currentWidth: number, currentHeight: number): void; - } - - export class LensFlarePlugin implements RendererPlugin { - constructor(); - - init(renderer: Renderer): void; + export class LensFlarePlugin { + constructor(renderer: WebGLRenderer, flares: any[]); + render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; } - export class SpritePlugin implements RendererPlugin { - constructor(); + export class SpritePlugin { + constructor(renderer: WebGLRenderer, sprites: any[]); - init(renderer: Renderer): void; render(scene: Scene, camera: Camera, viewportWidth: number, viewportHeight: number): void; } // Scenes ///////////////////////////////////////////////////////////////////// + + /** + * Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras. + */ + export class Scene extends Object3D { + constructor(); + + /** + * A fog instance defining the type of fog that affects everything rendered in the scene. Default is null. + */ + fog: IFog; + + /** + * If not null, it will force everything in the scene to be rendered with that material. Default is null. + */ + overrideMaterial: Material; + autoUpdate: boolean; + + copy(source: Scene, recursive?: boolean): Scene; + } export interface IFog { name:string; @@ -5055,7 +5341,6 @@ declare namespace THREE { clone():IFog; } - /** * This class contains the parameters that define linear fog, i.e., that grows linearly denser with the distance. */ @@ -5101,103 +5386,8 @@ declare namespace THREE { clone(): FogExp2; } - /** - * Scenes allow you to set up what and where is to be rendered by three.js. This is where you place objects, lights and cameras. - */ - export class Scene extends Object3D { - constructor(); - - /** - * A fog instance defining the type of fog that affects everything rendered in the scene. Default is null. - */ - fog: IFog; - - /** - * If not null, it will force everything in the scene to be rendered with that material. Default is null. - */ - overrideMaterial: Material; - autoUpdate: boolean; - - copy(source: Scene): Scene; - } - // Textures ///////////////////////////////////////////////////////////////////// - export class CanvasTexture extends Texture { - constructor( - canvas: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - - needsUpdate: boolean; - } - - export class CompressedTexture extends Texture { - constructor( - mipmaps: ImageData[], - width: number, - height: number, - format?: PixelFormat, - type?: TextureDataType, - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - anisotropy?: number - ); - - image: { width: number; height: number; }; - mipmaps: ImageData[]; - flipY: boolean; - generateMipmaps: boolean; - } - - export class CubeTexture extends Texture { - constructor( - images: any[], // HTMLImageElement or HTMLCanvasElement - mapping?: Mapping, - wrapS?: Wrapping, - wrapT?: Wrapping, - magFilter?: TextureFilter, - minFilter?: TextureFilter, - format?: PixelFormat, - type?: TextureDataType, - anisotropy?: number - ); - - images: any[]; - - copy(source: CubeTexture): CubeTexture; - } - - export class DataTexture extends Texture { - constructor( - data: ImageData, - width: number, - height: number, - format: PixelFormat, - type: TextureDataType, - mapping: Mapping, - wrapS: Wrapping, - wrapT: Wrapping, - magFilter: TextureFilter, - minFilter: TextureFilter, - anisotropy?: number - ); - - image: { data: ImageData; width: number; height: number; }; - magFilter: TextureFilter; - minFilter: TextureFilter; - flipY: boolean; - generateMipmaps: boolean; - } + export let TextureIdCount: number; export class Texture { constructor( @@ -5242,7 +5432,7 @@ declare namespace THREE { copy(source: Texture): Texture; toJSON(meta: any): any; dispose(): void; - transformUv( uv: Vector ): void; + transformUv(uv: Vector): void; // EventDispatcher mixins addEventListener(type: string, listener: (event: any) => void ): void; @@ -5251,7 +5441,84 @@ declare namespace THREE { dispatchEvent(event: { type: string; target: any; }): void; } - class VideoTexture extends Texture { + export class CanvasTexture extends Texture { + constructor( + canvas: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + clone(): CanvasTexture; + copy(source: CanvasTexture): CanvasTexture; + } + + export class CubeTexture extends Texture { + constructor( + images: any[], // HTMLImageElement or HTMLCanvasElement + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + format?: PixelFormat, + type?: TextureDataType, + anisotropy?: number + ); + + images: any[]; + + copy(source: CubeTexture): CubeTexture; + } + + export class CompressedTexture extends Texture { + constructor( + mipmaps: ImageData[], + width: number, + height: number, + format?: PixelFormat, + type?: TextureDataType, + mapping?: Mapping, + wrapS?: Wrapping, + wrapT?: Wrapping, + magFilter?: TextureFilter, + minFilter?: TextureFilter, + anisotropy?: number + ); + + image: { width: number; height: number; }; + + clone(): CompressedTexture; + copy(source: CompressedTexture): CompressedTexture; + } + + export class DataTexture extends Texture { + constructor( + data: ImageData, + width: number, + height: number, + format: PixelFormat, + type: TextureDataType, + mapping: Mapping, + wrapS: Wrapping, + wrapT: Wrapping, + magFilter: TextureFilter, + minFilter: TextureFilter, + anisotropy?: number + ); + + image: { data: ImageData; width: number; height: number; }; + + clone(): DataTexture; + copy(source: DataTexture): DataTexture; + } + + export class VideoTexture extends Texture { constructor( video: HTMLVideoElement, mapping?: Mapping, @@ -5264,64 +5531,61 @@ declare namespace THREE { anisotropy?: number ); - generateMipmaps: boolean; + clone(): VideoTexture; + copy(source: VideoTexture): VideoTexture; } // Extras ///////////////////////////////////////////////////////////////////// - export var CurveUtils: { - tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; + export namespace CurveUtils { + export function tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; + export function tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; + export function tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; + export function interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; } - // deprecated. - export var ImageUtils: { - crossOrigin: string; + export namespace ImageUtils { // deprecated + export let crossOrigin: string; - // deprecated. - loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; + export function loadTexture(url: string, mapping?: Mapping, onLoad?: (texture: Texture) => void, onError?: (message: string) => void): Texture; + export function loadTextureCube(array: string[], mapping?: Mapping, onLoad?: (texture: Texture) => void , onError?: (message: string) => void ): Texture; + } - // deprecated. - loadTextureCube(array: string[], mapping?: Mapping, onLoad?: (texture: Texture) => void , onError?: (message: string) => void ): Texture; + export namespace SceneUtils { + export function createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; + export function detach(child: Object3D, parent: Object3D, scene: Scene): void; + export function attach(child: Object3D, scene: Scene, parent: Object3D): void; + } - // deprecated. - getNormalMap(image: HTMLImageElement, depth?: number): HTMLCanvasElement; - - // deprecated. - generateDataTexture(width: number, height: number, color: Color): DataTexture; - }; - - export var SceneUtils: { - createMultiMaterialObject(geometry: Geometry, materials: Material[]): Object3D; - detach(child: Object3D, parent: Object3D, scene: Scene): void; - attach(child: Object3D, scene: Scene, parent: Object3D): void; - }; - - export var ShapeUtils: { - area( contour: number[] ): number; - triangulate( contour: number[], indices: boolean ): number[]; - triangulateShape( contour: number[], holes: any[] ): number[]; - isClockWise( pts: number[] ): boolean; - b2( t: number, p0: number, p1: number, p2: number ): number; - b3( t: number, p0: number, p1: number, p2: number, p3: number ): number; - }; + export namespace ShapeUtils { + export function area(contour: number[]): number; + export function triangulate(contour: number[], indices: boolean): number[]; + export function triangulateShape(contour: number[], holes: any[]): number[]; + export function isClockWise(pts: number[]): boolean; + export function b2(t: number, p0: number, p1: number, p2: number): number; + export function b3(t: number, p0: number, p1: number, p2: number, p3: number): number; + } // Extras / Audio ///////////////////////////////////////////////////////////////////// export class Audio extends Object3D { constructor(listener: AudioListener); + type: string; context: AudioContext; source: AudioBufferSourceNode; gain: GainNode; - panner: PannerNode; autoplay: boolean; startTime: number; playbackRate: number; + hasPlaybackControl: boolean; isPlaying: boolean; + sourceType: string; + filter: any; + getOutput(): GainNode; load(file: string): Audio; + setNodeSource(audioNode: AudioBufferSourceNode): Audio; + setBuffer(audioBuffer: AudioBuffer): Audio; play(): void; pause(): void; stop(): void; @@ -5331,16 +5595,46 @@ declare namespace THREE { getFilter(): any; setPlaybackRate(value: number): void; getPlaybackRate(): number; - + onEnded(): void; setLoop(value: boolean): void; getLoop(): boolean; + setVolume(value: number): void; + getVolume(): number; + } + + export class AudioAnalyser { + constructor(audio: any, fftSize: number); + + analyser: any; + data: Uint8Array; + + getData(): Uint8Array; + } + + export class AudioBuffer { + constructor(context: any); + + context: any; + ready: boolean; + readyCallbacks: Function[]; + + load(file: string): AudioBuffer; + onReady(callback: Function): void; + } + + export class PositionalAudio extends Audio { + constructor(listener: AudioListener); + + panner: PannerNode; + setRefDistance(value: number): void; getRefDistance(): number; setRolloffFactor(value: number): void; getRolloffFactor(): number; - setVolume(value: number): void; - getVolume(): number; - updateMatrixWorld(force?: boolean): void; + setDistanceModel(value: number): void; + getDistanceModel(): number; + setMaxDistance(value: number): void; + getMaxDistance(): number; } export class AudioListener extends Object3D { @@ -5348,8 +5642,14 @@ declare namespace THREE { type: string; context: AudioContext; + gain: GainNode; - updateMatrixWorld(force?: boolean): void; + getInput(): GainNode; + removeFilter(): void; + setFilter(value: any): void; + getFilter(): any; + setMasterVolume(value: number): void; + getMasterVolume(): number; } // Extras / Core ///////////////////////////////////////////////////////////////////// @@ -5418,22 +5718,6 @@ declare namespace THREE { static create(constructorFunc: Function, getPointFunc: Function): Function; } - export var CurveUtils: { - tangentQuadraticBezier(t: number, p0: number, p1: number, p2: number): number; - tangentCubicBezier(t: number, p0: number, p1: number, p2: number, p3: number): number; - tangentSpline(t: number, p0: number, p1: number, p2: number, p3: number): number; - interpolate(p0: number, p1: number, p2: number, p3: number, t: number): number; - }; - - export interface BoundingBox { - minX: number; - minY: number; - minZ?: number; - maxX: number; - maxY: number; - maxZ?: number; - } - export class CurvePath extends Curve { constructor(); @@ -5484,9 +5768,9 @@ declare namespace THREE { absarc(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean): void; ellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; absellipse(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number): void; - getSpacedPoints(divisions?: number, closedPath?: boolean): Vector2[]; + getSpacedPoints(divisions?: number): Vector2[]; getPoints(divisions?: number, closedPath?: boolean): Vector2[]; - toShapes(): Shape[]; + toShapes(isCCW: boolean, noHoles: any): Shape[]; } /** @@ -5505,24 +5789,20 @@ declare namespace THREE { holes: Vector2[][]; }; extractPoints(divisions: number): Vector2[]; - } // Extras / Curves ///////////////////////////////////////////////////////////////////// - export class ArcCurve extends EllipseCurve { - constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); - } - export class CatmullRomCurve3 extends Curve { - constructor(); - } - - export class ClosedSplineCurve3 extends Curve { constructor(points?: Vector3[]); points: Vector3[]; + + getPoint(t: number): Vector3; } + export class ClosedSplineCurve3 extends CatmullRomCurve3 {} // deprecated, use CatmullRomCurve3 + export class SplineCurve3 extends CatmullRomCurve3 {} // will be deprecated, use CatmullRomCurve3 + export class CubicBezierCurve extends Curve { constructor(v0: Vector2, v1: Vector2, v2: Vector2, v3: Vector2); @@ -5531,6 +5811,7 @@ declare namespace THREE { v2: Vector2; v3: Vector2; } + export class CubicBezierCurve3 extends Curve { constructor(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3); @@ -5538,7 +5819,10 @@ declare namespace THREE { v1: Vector3; v2: Vector3; v3: Vector3; + + getPoint(t: number): Vector3; } + export class EllipseCurve extends Curve { constructor(aX: number, aY: number, xRadius: number, yRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean, aRotation: number); @@ -5551,19 +5835,26 @@ declare namespace THREE { aClockwise: boolean; aRotation: number; } + export class ArcCurve extends EllipseCurve { + constructor(aX: number, aY: number, aRadius: number, aStartAngle: number, aEndAngle: number, aClockwise: boolean ); + } + export class LineCurve extends Curve { constructor( v1: Vector2, v2: Vector2 ); v1: Vector2; v2: Vector2; - } + export class LineCurve3 extends Curve { - constructor( v1: Vector3, v2: Vector3 ); + constructor(v1: Vector3, v2: Vector3); v1: Vector3; v2: Vector3; + + getPoint(t: number): Vector3; } + export class QuadraticBezierCurve extends Curve { constructor( v0: Vector2, v1: Vector2, v2: Vector2 ); @@ -5571,23 +5862,23 @@ declare namespace THREE { v1: Vector2; v2: Vector2; } + export class QuadraticBezierCurve3 extends Curve { - constructor( v0: Vector3, v1: Vector3, v2: Vector3 ); + constructor(v0: Vector3, v1: Vector3, v2: Vector3); v0: Vector3; v1: Vector3; v2: Vector3; + + getPoint(t: number): Vector3; } + export class SplineCurve extends Curve { - constructor( points?: Vector2[] ); + constructor(points?: Vector2[]); - points:Vector2[]; - } - export class SplineCurve3 extends Curve { - constructor( points?: Vector3[] ); - - points:Vector3[]; + points: Vector2[]; } + // Extras / Geomerties ///////////////////////////////////////////////////////////////////// /** @@ -5612,10 +5903,26 @@ declare namespace THREE { heightSegments: number; depthSegments: number; }; + widthSegments: number + heightSegments: number; + depthSegments: number; clone(): BoxGeometry; } + export class CubeGeometry extends BoxGeometry {} // deprecated, use BoxGeometry + + export class CircleGeometry extends Geometry { + constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); + + parameters: { + radius: number; + segments: number; + thetaStart: number; + thetaLength: number; + }; + } + export class CircleBufferGeometry extends Geometry { constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); @@ -5625,25 +5932,6 @@ declare namespace THREE { thetaStart: number; thetaLength: number; }; - - clone(): CircleBufferGeometry; - } - - export class CircleGeometry extends Geometry { - constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number); - - parameters: { - radius: number; - segments: number; - thetaStart: number; - thetaLength: number; - }; - - clone(): CircleGeometry; - } - - // deprecated - export class CubeGeometry extends BoxGeometry { } export class CylinderGeometry extends Geometry { @@ -5667,8 +5955,6 @@ declare namespace THREE { thetaStart: number; thetaLength: number; }; - - clone(): CylinderGeometry; } export class DodecahedronGeometry extends Geometry { @@ -5678,8 +5964,6 @@ declare namespace THREE { radius: number; detail: number; }; - - clone(): DodecahedronGeometry; } export class EdgesGeometry extends BufferGeometry { @@ -5703,8 +5987,6 @@ declare namespace THREE { export class IcosahedronGeometry extends PolyhedronGeometry { constructor(radius: number, detail: number); - - clone(): IcosahedronGeometry; } export class LatheGeometry extends Geometry { @@ -5720,8 +6002,6 @@ declare namespace THREE { export class OctahedronGeometry extends PolyhedronGeometry { constructor(radius: number, detail: number); - - clone(): OctahedronGeometry; } export class ParametricGeometry extends Geometry { @@ -5743,8 +6023,6 @@ declare namespace THREE { widthSegments: number; heightSegments: number; }; - - clone(): PlaneBufferGeometry; } export class PlaneGeometry extends Geometry { @@ -5756,8 +6034,6 @@ declare namespace THREE { widthSegments: number; heightSegments: number; }; - - clone(): PlaneGeometry; } export class PolyhedronGeometry extends Geometry { @@ -5769,8 +6045,7 @@ declare namespace THREE { radius: number; detail: number; }; - - clone(): PolyhedronGeometry; + boundingSphere: Sphere; } export class RingGeometry extends Geometry { @@ -5784,20 +6059,16 @@ declare namespace THREE { thetaStart: number; thetaLength: number; }; - - clone(): RingGeometry; } export class ShapeGeometry extends Geometry { constructor(shape: Shape, options?: any); constructor(shapes: Shape[], options?: any); - addShapeList(shapes: Shape[], options: any): ShapeGeometry; addShape(shape: Shape, options?: any): void; } - export class SphereBufferGeometry extends BufferGeometry { constructor(radius: number, widthSegments?: number, heightSegments?: number, phiStart?: number, phiLength?: number, thetaStart?: number, thetaLength?: number); @@ -5810,8 +6081,6 @@ declare namespace THREE { thetaStart: number; thetaLength: number; }; - - clone(): SphereBufferGeometry; } /** @@ -5844,8 +6113,30 @@ declare namespace THREE { export class TetrahedronGeometry extends PolyhedronGeometry { constructor(radius?: number, detail?: number); + } - clone(): TetrahedronGeometry; + export interface TextGeometryParameters { + font: Font; + site: number; + height: number; + curveSegments: number; + bevelEnabled: boolean; + bevelThickness: number; + bevelSize: number; + } + + export class TextGeometry extends ExtrudeGeometry { + constructor(text: string, parameters?: TextGeometryParameters); + + parameters: { + font: Font; + site: number; + height: number; + curveSegments: number; + bevelEnabled: boolean; + bevelThickness: number; + bevelSize: number; + } } export class TorusGeometry extends Geometry { @@ -5858,8 +6149,6 @@ declare namespace THREE { tubularSegments: number; arc: number; }; - - clone(): TorusGeometry; } export class TorusKnotGeometry extends Geometry { @@ -5874,11 +6163,8 @@ declare namespace THREE { q: number; heightScale: number; }; - - clone(): TorusKnotGeometry; } - export class TubeGeometry extends Geometry { constructor(path: Path, segments?: number, radius?: number, radiusSegments?: number, closed?: boolean, taper?: (u: number) => number); @@ -5897,11 +6183,9 @@ declare namespace THREE { static NoTaper(u?: number): number; static SinusoidalTaper(u: number): number; static FrenetFrames(path: Path, segments: number, closed: boolean): void; - - clone(): TubeGeometry; } - export class WireframeGeometry extends BufferGeometry{ + export class WireframeGeometry extends BufferGeometry { constructor(geometry: Geometry | BufferGeometry); } @@ -5959,7 +6243,6 @@ declare namespace THREE { export class EdgesHelper extends LineSegments { constructor(object: Object3D, hex?: number, thresholdAngle?: number); - } export class FaceNormalsHelper extends LineSegments { @@ -5979,6 +6262,7 @@ declare namespace THREE { setColors(colorCenterLine: number, colorGrid: number): void; } + export class HemisphereLightHelper extends Object3D { constructor(light: Light, sphereSize: number); @@ -6030,7 +6314,6 @@ declare namespace THREE { export class WireframeHelper extends LineSegments { constructor(object: Object3D, hex?: number); - } // Extras / Objects ///////////////////////////////////////////////////////////////////// @@ -6039,7 +6322,7 @@ declare namespace THREE { constructor(material: Material); material: Material; - render(renderCallback:Function): void; + render(renderCallback: Function): void; } export interface MorphBlendMeshAnimation { From 1d3dd1edeef5751eb0415644d20ec1b52e44f19e Mon Sep 17 00:00:00 2001 From: Yukiya Nakagawa Date: Sat, 19 Mar 2016 23:36:02 +0900 Subject: [PATCH 04/53] Update GeoJSON definition with generics --- geojson/geojson-tests.ts | 2 +- geojson/geojson.d.ts | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index ed953520b..611db7d52 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -54,7 +54,7 @@ var featureCollection: GeoJSON.FeatureCollection = { } } -var feature: GeoJSON.Feature = { +var feature: GeoJSON.Feature = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], geometry: { diff --git a/geojson/geojson.d.ts b/geojson/geojson.d.ts index f74778315..d77de1fe8 100644 --- a/geojson/geojson.d.ts +++ b/geojson/geojson.d.ts @@ -90,9 +90,9 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#feature-objects */ - export interface Feature extends GeoJsonObject + export interface Feature extends GeoJsonObject { - geometry: GeometryObject; + geometry: T; properties: any; id?: string; } @@ -100,9 +100,9 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#feature-collection-objects */ - export interface FeatureCollection extends GeoJsonObject + export interface FeatureCollection extends GeoJsonObject { - features: Feature[]; + features: Feature[]; } /*** From 25a296c2e959f90658d1c3b1572fab75fa458557 Mon Sep 17 00:00:00 2001 From: Yukiya Nakagawa Date: Sun, 20 Mar 2016 01:03:52 +0900 Subject: [PATCH 05/53] Add type definitions for turf --- turf/turf-tests.ts | 6 +-- turf/turf.d.ts | 118 ++++++++++++++++++++++----------------------- 2 files changed, 62 insertions(+), 62 deletions(-) diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index a262b359e..d0fc95ba1 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -441,11 +441,11 @@ var value = "oak"; var filtered = turf.filter(features, key, value); // -- Test random -- -var points = turf.random('points', 100, { +var randomPoints = turf.random('points', 100, { bbox: [-70, 40, -60, 60] }); -var points = turf.random('points', 100, { +var randomPoints = turf.random('points', 100, { bbox: [-70, 40, -60, 60], num_vertices: 2, max_radial_length: 10 @@ -455,7 +455,7 @@ var points = turf.random('points', 100, { var filtered = turf.remove(points, 'marker-color', '#00f'); // -- Test sample -- -var points = turf.random('points', 1000); +var randomPoints = turf.random('points', 1000); var sample = turf.sample(points, 10); /////////////////////////////////////////// diff --git a/turf/turf.d.ts b/turf/turf.d.ts index 6bb00e316..6ed1d617a 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -18,7 +18,7 @@ declare namespace turf { * @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; + 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. @@ -28,7 +28,7 @@ declare namespace turf { * @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; + 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. @@ -37,7 +37,7 @@ declare namespace turf { * @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; + 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. @@ -47,7 +47,7 @@ declare namespace turf { * @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; + 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. @@ -57,7 +57,7 @@ declare namespace turf { * @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; + 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. @@ -67,7 +67,7 @@ declare namespace turf { * @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; + 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. @@ -77,7 +77,7 @@ declare namespace turf { * @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; + 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. @@ -87,7 +87,7 @@ declare namespace turf { * @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; + 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. @@ -97,7 +97,7 @@ declare namespace turf { * @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; + function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Measurement @@ -110,21 +110,21 @@ declare namespace 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; + 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; + 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; + function bboxPolygon(bbox: Array): GeoJSON.Feature; /** * Takes two points and finds the geographic bearing between them. @@ -132,14 +132,14 @@ declare namespace turf { * @param end Ending point * @returns Bearing in decimal degrees */ - function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + 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; + function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. @@ -147,7 +147,7 @@ declare namespace turf { * @param features Input features * @returns The centroid of the input features */ - function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + 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. @@ -158,7 +158,7 @@ declare namespace turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Destination point */ - function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + 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. @@ -168,21 +168,21 @@ declare namespace 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; + 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; + 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; + function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; /** * Takes a line and measures its length in the specified units. @@ -190,7 +190,7 @@ declare namespace turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Length of the input line */ - function lineDistance(line: GeoJSON.Feature, units: string): number; + function lineDistance(line: GeoJSON.Feature, units: string): number; /** * Takes two points and returns a point midway between them. @@ -198,7 +198,7 @@ declare namespace turf { * @param pt2 Second point * @returns A point midway between pt1 and pt2 */ - function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + 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. @@ -206,7 +206,7 @@ declare namespace 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; + 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. @@ -235,7 +235,7 @@ declare namespace 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; + 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. @@ -244,7 +244,7 @@ declare namespace turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Buffered features */ - function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.Feature | GeoJSON.FeatureCollection; + 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. @@ -253,14 +253,14 @@ declare namespace 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; + 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; + function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Finds the difference between two polygons by clipping the second polygon from the first. @@ -268,7 +268,7 @@ declare namespace 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; + function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; /** * Takes two polygons and finds their intersection. @@ -279,7 +279,7 @@ declare namespace turf { * 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; + function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; /** * Takes a set of polygons and returns a single merged polygon feature. @@ -287,7 +287,7 @@ declare namespace turf { * @param fc Input polygons * @returns Merged polygon or multipolygon */ - function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a LineString or Polygon and returns a simplified version. @@ -297,7 +297,7 @@ declare namespace 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; + 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. @@ -306,7 +306,7 @@ declare namespace turf { * @param poly2 Another input polygon * @returns A combined Polygon or MultiPolygon feature */ - function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Misc @@ -317,28 +317,28 @@ declare namespace turf { * @param fc A FeatureCollection of any type * @returns A FeatureCollection of corresponding type to input */ - function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + 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; + 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; + 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; + 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. @@ -347,7 +347,7 @@ declare namespace turf { * @param line Line to slice * @returns Sliced line */ - function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + 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. @@ -355,7 +355,7 @@ declare namespace 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; + function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Helper @@ -366,7 +366,7 @@ declare namespace turf { * @param features Input features * @returns A FeatureCollection of input features */ - function featurecollection(features: Array): GeoJSON.FeatureCollection; + function featurecollection(features: Array>): GeoJSON.FeatureCollection; /** * Creates a LineString based on a coordinate array. Properties can be added optionally. @@ -374,7 +374,7 @@ declare namespace turf { * @param [properties] An Object of key-value pairs to add as properties * @returns A LineString feature */ - function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; /** * Takes coordinates and properties (optional) and returns a new Point feature. @@ -382,7 +382,7 @@ declare namespace turf { * @param [properties] An Object of key-value pairs to add as properties * @returns A Point feature */ - function point(coordinates: Array, properties?: any): GeoJSON.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. @@ -390,7 +390,7 @@ declare namespace turf { * @param [properties] An Object of key-value pairs to add as properties * @returns A Polygon feature */ - function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; ////////////////////////////////////////////////////// // Data @@ -403,7 +403,7 @@ declare namespace turf { * @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; + function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; /** * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. @@ -415,7 +415,7 @@ declare namespace turf { * - 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; + 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. @@ -424,7 +424,7 @@ declare namespace turf { * @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; + 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. @@ -432,7 +432,7 @@ declare namespace turf { * @param n Number of features to select * @returns A FeatureCollection with n features */ - function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Interpolation @@ -445,7 +445,7 @@ declare namespace turf { * @param units Used in calculating cellWidth ('miles' or 'kilometers') * @returns A hexagonal grid */ - function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; /** * Takes points with z-values and an array of value breaks and generates isolines. @@ -455,7 +455,7 @@ declare namespace turf { * @param breaks Where to draw contours * @returns Isolines */ - function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + 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. @@ -464,7 +464,7 @@ declare namespace turf { * @param triangle A Polygon feature with three vertices * @returns The z-value for interpolatedPoint */ - function planepoint(interpolatedPoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; + 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. @@ -473,7 +473,7 @@ declare namespace turf { * @param units Used in calculating cellWidth ('miles' or 'kilometers') * @returns Grid of points */ - function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + 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. @@ -482,7 +482,7 @@ declare namespace turf { * @param units Used in calculating cellWidth ('miles' or 'kilometers') * @returns Grid of polygons */ - function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + 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. @@ -492,7 +492,7 @@ declare namespace 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; + 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. @@ -501,7 +501,7 @@ declare namespace turf { * @param units Used in calculating cellWidth ('miles' or 'kilometers') * @returns Grid of triangles */ - function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Joins @@ -514,7 +514,7 @@ declare namespace turf { * @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; + function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; /** * Takes a set of points and a set of polygons and performs a spatial join. @@ -524,7 +524,7 @@ declare namespace turf { * @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; + 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. @@ -532,7 +532,7 @@ declare namespace turf { * @param polygons Input polygons * @returns Points that land within at least one polygon */ - function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Classification @@ -545,7 +545,7 @@ declare namespace turf { * @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; + 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. @@ -553,7 +553,7 @@ declare namespace turf { * @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; + 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. @@ -562,7 +562,7 @@ declare namespace turf { * @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; + 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. @@ -572,5 +572,5 @@ declare namespace turf { * @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; + function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; } From c3d74dd8f25f3bb927cbd5e55370d358b5d60c1b Mon Sep 17 00:00:00 2001 From: Yukiya Nakagawa Date: Sun, 20 Mar 2016 01:43:54 +0900 Subject: [PATCH 06/53] Add generics for polyline --- polyline/polyline.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polyline/polyline.d.ts b/polyline/polyline.d.ts index 78fb292d1..17389ed7e 100644 --- a/polyline/polyline.d.ts +++ b/polyline/polyline.d.ts @@ -8,7 +8,7 @@ interface Polyline { decode(string: string, precision?: number): number[][]; encode(coordinate: number[][], precision?: number): string; - fromGeoJSON(geojson: GeoJSON.LineString | GeoJSON.Feature, precision?: number): string; + fromGeoJSON(geojson: GeoJSON.LineString | GeoJSON.Feature, precision?: number): string; } declare var polyline: Polyline; From b9faee43fd3e9e87f2cf34e6efd64a6ef89be576 Mon Sep 17 00:00:00 2001 From: Yukiya Nakagawa Date: Sun, 20 Mar 2016 01:46:42 +0900 Subject: [PATCH 07/53] fix test --- geojson/geojson-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index 611db7d52..ce38b654b 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -1,6 +1,6 @@ /// -var featureCollection: GeoJSON.FeatureCollection = { +var featureCollection: GeoJSON.FeatureCollection = { type: "FeatureCollection", features: [ { From 3dba657aa09f520072e02769f64b4ca026b9170e Mon Sep 17 00:00:00 2001 From: Jussi Kinnula Date: Mon, 21 Mar 2016 15:01:49 +0200 Subject: [PATCH 08/53] Add dotenv --- dotenv/dotenv-tests.ts | 15 +++++++++++++++ dotenv/dotenv.d.ts | 14 ++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 dotenv/dotenv-tests.ts create mode 100644 dotenv/dotenv.d.ts diff --git a/dotenv/dotenv-tests.ts b/dotenv/dotenv-tests.ts new file mode 100644 index 000000000..555c104c9 --- /dev/null +++ b/dotenv/dotenv-tests.ts @@ -0,0 +1,15 @@ +/// + +import dotenv = require('dotenv'); + +dotenv.config({ + silent: true +}); + +dotenv.config({ + path: '.env' +}) + +dotenv.config({ + encoding: 'utf8' +}) \ No newline at end of file diff --git a/dotenv/dotenv.d.ts b/dotenv/dotenv.d.ts new file mode 100644 index 000000000..f0633e88f --- /dev/null +++ b/dotenv/dotenv.d.ts @@ -0,0 +1,14 @@ +// Type definitions for dotenv 2.0.0 +// Project: https://github.com/bkeepers/dotenv +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/jussikinnula/DefinitelyTyped + +interface dotenvOptions { + silent?: boolean; + path?: string; + encoding?: string; +} + +declare module 'dotenv' { + export function config(options?: dotenvOptions): boolean; +} From ed673f6e649967f0f387b0d2a52ceeffb164902f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladimir=20=C4=90oki=C4=87?= Date: Wed, 23 Mar 2016 14:19:01 +0100 Subject: [PATCH 09/53] Initial commit of jsen (JSON Sentinel) typescript definition. --- jsen/jsen-tests.ts | 3503 ++++++++++++++++++++++++++++++++++++++++++++ jsen/jsen.d.ts | 42 + 2 files changed, 3545 insertions(+) create mode 100644 jsen/jsen-tests.ts create mode 100644 jsen/jsen.d.ts diff --git a/jsen/jsen-tests.ts b/jsen/jsen-tests.ts new file mode 100644 index 000000000..8504c0279 --- /dev/null +++ b/jsen/jsen-tests.ts @@ -0,0 +1,3503 @@ +/// + +// any +{ + // passes validation on any type + { + const schema = { type: "any" }; + const validate = jsen(schema); + + console.assert(validate(null)); + console.assert(validate(undefined)); + console.assert(validate(0)); + console.assert(validate('')); + console.assert(validate(Math.PI)); + console.assert(validate('abc')); + console.assert(validate(77)); + console.assert(validate(false)); + console.assert(validate(true)); + console.assert(validate({})); + console.assert(validate([])); + } +} + +// type: array +{ + // required + { + const schema = { type: 'array' }; + const validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + + console.assert(validate([])); + } + // nullable + { + const schema = { type: ['array', 'null'] }; + const validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(null)); + console.assert(validate([])); + } + + // type + { + const schema = { type: 'array' }; + const validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate(false)); + console.assert(!validate({})); + console.assert(!validate(Math.PI)); + + console.assert(validate([])); + } + + // minItems + { + const schema = { type: 'array', minItems: 3 }; + const validate = jsen(schema); + + console.assert(!validate([])); + console.assert(!validate([1, 2])); + + console.assert(validate([1, 2, 3])); + console.assert(validate([1, 2, 3, 4])); + } + + // maxItems + { + const schema = { type: 'array', maxItems: 3 }; + const validate = jsen(schema); + + console.assert(!validate([1, 2, 3, 4])); + + console.assert(validate([])); + console.assert(validate([1, 2, 3])); + } + + // items: object + { + let schema: any = { type: 'array', items: { type: 'string' } }; + let validate = jsen(schema); + + console.assert(!validate(null)); + console.assert(!validate([1])); + console.assert(!validate(['a', false, 'b'])); + console.assert(!validate(['a', 'b', 1])); + + console.assert(validate([])); + console.assert(validate(['a'])); + console.assert(validate(['a', 'b', 'c'])); + + schema = { + type: 'array', + items: { + type: 'object', + properties: { + strProp: { type: 'string' }, + boolProp: { type: 'boolean' } + }, + required: ['strProp'] + } + }; + + validate = jsen(schema); + + console.assert(!validate([123])); + console.assert(!validate([{}])); + console.assert(!validate([{ + strProp: 'value', + boolProp: 123 + }])); + + console.assert(validate([{ + strProp: 'value', + boolProp: false + }])); + } + + // items: array + { + const schema = { + type: 'array', + items: [ + { type: 'string' }, + { type: 'number' } + ] + }; + + const validate = jsen(schema); + + console.assert(!validate([1])); + console.assert(!validate([1, 'a'])); + + console.assert(validate([])); + console.assert(validate(['a'])); + console.assert(validate(['a', 1])); + console.assert(validate(['a', 1, null, 'b', 2])); + } + + // additionalItems: boolean + { + let schema: any = { type: 'array', additionalItems: false }; + let validate = jsen(schema); + + console.assert(validate([])); + console.assert(validate([1])); + console.assert(validate([1, 'a', true])); + + schema.items = { type: 'number' }; + validate = jsen(schema); + + console.assert(!validate(['a'])); + + console.assert(validate([])); + console.assert(validate([1])); + console.assert(validate([1, 2, 3])); + + schema.items = [ + { type: 'string' }, + { type: 'number' } + ]; + validate = jsen(schema); + + console.assert(!validate(['a', 1, 2])); + + console.assert(validate([])); + console.assert(validate(['a'])); + console.assert(validate(['a', 1])); + } + + // additionalItems: object + { + // when `items` is an object schema, `additionalItems` + // is ignored and must not validate against + let schema: any = { + type: 'array', + items: { + type: 'string' + }, + additionalItems: { + type: 'number' + } + }; + + let validate = jsen(schema); + + console.assert(!validate(['abc', 'def', 123])); + + // same as above description - only strings are valid + console.assert(validate(['abc', 'def'])); + + // when `items` is an array, any other positional + // data item must validate against `additionalItems` + schema.items = [ + { type: 'string' }, + { type: 'boolean' } + ]; + validate = jsen(schema); + + console.assert(!validate(['abc', false, 'def'])); + + console.assert(validate(['abc', false])); + console.assert(validate(['abc', false, 123])); + console.assert(validate(['abc', false, 123, Math.PI])); + + // when `additionalItems` is an empty object, anything is valid + schema.additionalItems = {}; + validate = jsen(schema); + + console.assert(validate(['abc', false, 'def', 123, {}, null])); + } + + // uniqueItems + { + let schema = { + type: 'array', + items: { type: 'number' }, + uniqueItems: false + }; + + let validate = jsen(schema); + + console.assert(validate([1, 2, 1])); + + schema.uniqueItems = true; + validate = jsen(schema); + + console.assert(!validate([1, 2, 1])); + + console.assert(validate([1, 2, 3])); + } +} + +// type: boolean +{ + // required + { + const schema = { type: 'boolean' }; + const validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + + console.assert(validate(false)); + console.assert(validate(true)); + } + + // nullable + { + const schema = { type: ['boolean', 'null'] }; + const validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(true)); + console.assert(validate(false)); + console.assert(validate(null)); + } + + // type + { + const schema = { type: 'boolean' }; + const validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate([])); + console.assert(!validate({})); + console.assert(!validate(Math.PI)); + + console.assert(validate(true)); + console.assert(validate(false)); + } +} + +// build +{ + // validator function has a build property + { + const validate = jsen({}); + + console.assert(typeof validate.build === 'function'); + console.assert(validate.build.length === 2); + } + + // returns default value from schema if initial undefined + { + const validate = jsen({ type: 'string', default: 'abc' }); + + console.assert(validate.build() === 'abc'); + console.assert(validate.build(undefined) === 'abc'); + } + + // does not modify initial defined value + { + const validate = jsen({ type: 'string', default: 'abc' }); + const initials = [ + null, + '', + 'string value', + true, + false, + 123, + Math.PI + ]; + + let obj: any; + + initials.forEach((initial) => { + obj = validate.build(initial); + console.assert(obj === initial); + }); + } + + // returns a copy of initial defined value + { + const validate = jsen({ type: 'string', default: 'abc' }); + const initials = [ + {}, + [], + new Date() + ]; + + let obj: any; + + initials.forEach((initial) => { + obj = validate.build(initial); + console.assert(obj !== initial); + console.assert(JSON.stringify(obj) === JSON.stringify(initial)); + }); + } + + // returns initial if no default in schema + { + const validate = jsen({}), + initials = [ + undefined, + null, + '', + 'string value', + true, + false, + 123, + Math.PI, + {}, + [], + new Date() + ]; + + let obj: any; + + initials.forEach((initial) => { + obj = validate.build(initial); + console.assert(JSON.stringify(obj) === JSON.stringify(initial)); + }); + } + + // returns the default value specified in schema + { + const schemas = [ + { default: null }, + { default: undefined }, + { default: '' }, + { default: 'abc' }, + { default: true }, + { default: false }, + { default: 123 }, + { default: Math.PI } + ]; + + let validate: IJsenValidator; + + schemas.forEach((schema) => { + validate = jsen(schema); + console.assert(validate.build() === schema.default); + }); + } + + // returns a copy of a default object or array in schema + { + const schemas = [ + { default: { a: { b: 123 } } }, + { default: [[1, 2, 3], { a: { b: 123 } }] }, + { default: /\d+/ }, + { default: new Date('05/14/2015') } + ]; + + let validate: IJsenValidator; + let def: any; + + schemas.forEach((schema) => { + validate = jsen(schema); + def = validate.build(); + + console.assert(def !== schema.default); + console.assert(JSON.stringify(def) === JSON.stringify(schema.default)); + }); + } + + // recursively collects default values + { + const schema: any = { + type: 'object', + default: {}, + properties: { + a: { + type: 'array', + default: [], + items: { + type: 'string' + } + }, + b: { + type: 'array', + default: [], + items: { + type: 'string', + default: 'abc' + } + }, + c: { + type: 'object', + default: {}, + properties: { + d: { + type: 'boolean', + default: false + }, + e: { + type: 'date', + default: new Date('05/14/2015') + }, + f: { + type: 'array', + default: [{}, {}], + items: [{ + type: 'object', + properties: { + g: { + type: 'string', + default: 'yes' + } + } + }, { + type: 'object', + properties: { + g: { + type: 'integer', + default: 0 + } + } + }, { + type: 'object', + properties: { + g: { + type: 'boolean', + default: true + } + } + }] + }, + h: { + type: 'array', + default: [{}, {}], + items: { + type: 'object', + properties: { + i: { + type: 'object', + default: { foo: 'bar' } + } + } + } + }, + i: { + type: 'object', + default: null, + properties: { + j: { + type: 'string', + default: 'baz' + } + } + } + } + }, + j: { + type: 'object', + properties: { + k: { + type: 'boolean', + default: false + } + } + } + } + }; + + const expected: any = { + a: [], + b: [], + c: { + d: false, + e: new Date('05/14/2015'), + f: [ + { g: 'yes' }, + { g: 0 } + ], + h: [ + { i: { foo: 'bar' } }, + { i: { foo: 'bar' } } + ], + i: null + } + }; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + + // merges default values with the initial values + { + const schemas = [ + { + properties: { + foo: { default: 'bar' } + } + }, + { + properties: { + foo: { default: 'bar' } + } + }, + { + properties: { + foo: { default: 'bar' } + } + }, + { + items: { + properties: { + foo: { default: 'bar' } + } + } + }, + { + items: { + properties: { + foo: { default: 'bar' } + } + } + }, + { + items: [ + { default: 'foo' }, + { default: 'bar' }, + { default: 'baz' } + ] + }, + { + items: [ + { default: 'foo' }, + { default: 'bar' }, + { default: 'baz' } + ] + } + ]; + + const defaults = [ + {}, + { foo: 'baz' }, + { x: 'yz' }, + [], + [{}], + [], + [null, {}, undefined, false] + ]; + + const expected = [ + { foo: 'bar' }, + { foo: 'baz' }, + { foo: 'bar', x: 'yz' }, + [], + [{ foo: 'bar' }], + ['foo', 'bar', 'baz'], + [null, {}, 'baz', false] + ]; + + let validate: IJsenValidator; + + schemas.forEach((schema, index) => { + validate = jsen(schema); + console.assert(JSON.stringify(validate.build(defaults[index])) === JSON.stringify(expected[index])); + }); + } + + // $ref + { + const schema = { + definitions: { + positiveInteger: { + type: 'integer', + minimum: 1, + default: 7 + } + }, + $ref: '#definitions/positiveInteger' + }; + + const validate = jsen(schema); + console.assert(validate.build() === 7); + } + + // object + { + // clones default object and subproperties recursively + { + const schema = { + default: {}, + properties: { + foo: { + type: 'string', + default: 'bar' + } + } + }; + + const expected = { foo: 'bar' }; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + + // does not recursively assign defaults of children if parent default is not an object + { + const schema: any = { + default: [], + properties: { + foo: { + type: 'string', + default: 'bar' + } + } + }; + + const expected: any = []; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + } + + // array + { + // does not add new elements to default array: items schema is an object + { + const schema: any = { + default: [], + items: { + type: 'string', + default: 'bar' + } + }; + + const expected: any = []; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + + // adds new elements to default array: items schema is an array + { + const schema: any = { + default: [], + items: [{ + type: 'string', + default: 'bar' + }] + }; + + const expected = ['bar']; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + + // adds default values to already existing child items of compatible type only: items schema is an object + { + const schema: any = { + default: [{}, null, []], + items: { + properties: { + foo: { + type: 'string', + default: 'bar' + } + } + } + }; + + const expected: any = [{ foo: 'bar' }, null, []]; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + + // adds default values to already existing child items of compatible type only: items schema is an array + { + const schema: any = { + default: [{}, null, {}, undefined], + items: [ + { + properties: { + foo: { + type: 'string', + default: 'bar' + } + } + }, + { default: 'abc' }, + { default: 123 }, + { default: 123 } + ] + }; + + const expected = [{ foo: 'bar' }, null, {}, 123]; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + + // does not assign default child items if parent default is not an array + { + const schema: any = { + default: 'foobar', + items: { + type: 'string', + default: 'bar' + } + }; + + const expected = 'foobar'; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build()) === JSON.stringify(expected)); + } + } + + // option: copy + { + // returns deep copy of the initial object by default + { + const schema = {}; + const initial = {}; + + const validate = jsen(schema); + + console.assert(JSON.stringify(validate.build(initial)) === JSON.stringify(initial)); + console.assert(validate.build(initial) !== initial); + } + + // modifies the initial object when copy = false + { + const schema = { + properties: { + a: { default: 'foo' }, + b: { + items: { + properties: { + c: { default: 'bar' }, + d: { default: 'baz' } + } + } + } + } + }; + + const initial = { b: [{ d: 'xyz' }] }; + const expected = { a: 'foo', b: [{ c: 'bar', d: 'xyz' }] }; + + const validate = jsen(schema); + const actual = validate.build(initial, { copy: false }); + + console.assert(JSON.stringify(actual) === JSON.stringify(expected)); + console.assert(actual === initial); + } + } + + // option: additionalProperties + { + // includes by default + { + const schema = { + properties: { + foo: {} + } + }; + + const initial = { foo: 1, bar: 2 }; + const expected = { foo: 1, bar: 2 }; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build(initial)) === JSON.stringify(expected)); + } + + // excludes when schema.additionalProperties = false + { + const schema = { + additionalProperties: false, + properties: { + foo: {} + } + }; + + const initial = { foo: 1, bar: 2 }; + const expected = { foo: 1 }; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build(initial)) === JSON.stringify(expected)); + } + + // removes from the initial object when schema.additionalProperties = false and options.copy = false + { + const schema = { + additionalProperties: false, + properties: { + foo: {} + } + }; + + const initial = { foo: 1, bar: 2 }; + const expected = { foo: 1 }; + + const validate = jsen(schema); + const actual = validate.build(initial, { copy: false }); + + console.assert(actual === initial); + console.assert(JSON.stringify(actual) === JSON.stringify(expected)); + } + + // removes from the initial object when options.additionalProperties = false and options.copy = false + { + const schema = { + properties: { + foo: {} + } + }; + + const initial = { foo: 1, bar: 2 }; + const expected = { foo: 1 }; + + const validate = jsen(schema); + const actual = validate.build(initial, { + copy: false, + additionalProperties: false + }); + + console.assert(actual === initial); + console.assert(JSON.stringify(actual) === JSON.stringify(expected)); + } + + // schema.additionalProperties takes precedence + { + const schema = { + additionalProperties: true, + properties: { + foo: {} + } + }; + + const initial = { foo: 1, bar: 2 }; + const expected = { foo: 1, bar: 2 }; + + const validate = jsen(schema); + console.assert(JSON.stringify(validate.build(initial, { additionalProperties: false })) === JSON.stringify(expected)); + } + } +} + +// clone +{ + const clone = jsen.clone; + + // string + { + console.assert(clone('abc') === 'abc'); + } + + // number + { + console.assert(clone(123) === 123); + } + + // integer + { + console.assert(clone(Math.PI) === Math.PI); + } + + // boolean + { + console.assert(clone(false) === false); + } + + // function + { + const func = () => { + }; + console.assert(clone(func) === func); + } + + // regexp + { + const regex = /a/gim; + console.assert(clone(regex) !== regex); + console.assert(clone(regex).toString() === regex.toString()); + } + + // date + { + const today = new Date('05/14/2015'); + console.assert(clone(today) !== today); + console.assert(clone(today).toJSON() === today.toJSON()); + } + + // null + { + console.assert(clone(null) === null); + } + + // undefined + { + console.assert(clone(undefined) === undefined); + } + + // object + { + const obj = { a: 1, b: 'a', c: false, d: { e: Math.PI, f: [1, 2, 3] } }; + console.assert(clone(obj) !== obj); + console.assert(JSON.stringify(clone(obj)) === JSON.stringify(obj)); + } + + // array + { + const arr = [1, 'a', false, { d: [1, 2, 3] }]; + console.assert(clone(arr) !== arr); + console.assert(JSON.stringify(clone(arr)) === JSON.stringify(arr)); + } +} + +// type: date +{ + // required + { + const schema = { type: 'date' }; + const validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + + console.assert(validate(new Date())); + } + + // nullable + { + const schema = { type: ['date', 'null'] }; + const validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(new Date())); + console.assert(validate(null)); + } + + // type + { + const schema = { type: 'date' }; + const validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate([])); + console.assert(!validate({})); + console.assert(!validate(Math.PI)); + + console.assert(validate(new Date())); + } +} + +// equal +{ + const equal = jsen.equal; + // string + { + console.assert(equal('a', 'a')); + console.assert(!equal('a', 'b')); + } + + // number + { + console.assert(equal(123, 123)); + console.assert(equal(Math.PI, Math.PI)); + console.assert(!equal(Math.PI, Math.E)); + } + + // boolean + { + console.assert(equal(true, true)); + console.assert(!equal(true, false)); + } + + // null + { + console.assert(equal(null, null)); + console.assert(!equal(null, undefined)); + } + + // undefined + { + console.assert(equal(undefined, undefined)); + console.assert(!equal(null, undefined)); + } + + // function + { + const f1 = () => { + }; + const f2 = () => { + }; + const f3 = f1; + + // two functions are only equal if they + // reference the same function object + console.assert(equal(f1, f3)); + console.assert(!equal(f1, f2)); + } + + // array + { + const f = () => { + }; + const obj1 = { a: 123, b: 'abc', c: f }; + const obj2 = { a: 123, b: 'abc', c: f }; + const arr1 = [1, 'a', f, obj1]; + const arr2 = [1, 'a', f, obj1]; + const arr3 = [1, 'a', f]; + const arr4 = [1, 'a', f, obj2]; + + console.assert(equal(arr1, arr2)); + console.assert(equal(arr1, arr4)); + + console.assert(!equal(arr1, arr3)); + } + + // object + { + const a = { a: 123, b: ['abc'], c: {} }; + const b = { b: ['abc'], c: {}, a: 123 }; + const c = a; + const d: any = { a: 123, b: ['abc'], c: { d: undefined } }; + + console.assert(equal(a, b)); + console.assert(equal(a, c)); + + console.assert(!equal(a, d)); + } + + // regexp + { + const a = /a+/gim; + const b = new RegExp('a+', 'gim'); + const c = /a/gim; + const d = a; + + console.assert(equal(a, b)); + console.assert(equal(a, d)); + + console.assert(!equal(a, c)); + } +} + +// error +{ + // errors is empty array before validation + { + const schema = { type: 'number' }; + const validate = jsen(schema); + + console.assert(Array.isArray(validate.errors)); + console.assert(validate.errors.length === 0); + } + + // no errors on successful validation + { + const schema = { type: 'number' }; + const validate = jsen(schema); + const valid = validate(123); + + console.assert(valid); + console.assert(Array.isArray(validate.errors)); + console.assert(validate.errors.length === 0); + } + + // has errors when validation unsuccessful + { + const schema = { type: 'number' }; + const validate = jsen(schema); + const valid = validate('123'); + + console.assert(!valid); + console.assert(Array.isArray(validate.errors)); + console.assert(validate.errors.length === 1); + } + + // clears errors on successive validation calls + { + const schema = { type: 'number' }; + const validate = jsen(schema); + + validate('123'); + console.assert(Array.isArray(validate.errors)); + console.assert(validate.errors.length === 1); + + validate(123); + console.assert(Array.isArray(validate.errors)); + console.assert(validate.errors.length === 0); + + validate('123'); + console.assert(Array.isArray(validate.errors)); + console.assert(validate.errors.length === 1); + } + + // two successive runs return different arrays + { + const schema = { type: 'number' }; + const validate = jsen(schema); + + let previous: any; + + validate('123'); + console.assert(validate.errors.length === 1); + previous = validate.errors; + + validate('123'); + console.assert(validate.errors.length === 1); + + console.assert(validate.errors !== previous); + console.assert(JSON.stringify(validate.errors) === JSON.stringify(previous)); + } + + // error object + { + const schemas = [ + { + type: 'number' + }, + + { + type: 'object', + properties: { + a: { + type: 'string' + } + } + }, + + { + type: 'array', + uniqueItems: true + }, + + { + type: 'array', + items: { + maximum: 10 + } + }, + + { + type: 'object', + properties: { + a: { + type: 'array', + items: [{ + type: 'object', + properties: { + b: { + multipleOf: 7 + } + } + }] + } + } + }, + + { + allOf: [ + { minimum: 5 }, + { maximum: 10 } + ] + }, + + { + type: 'object', + properties: { + a: { + anyOf: [ + { type: 'string' }, + { type: 'number' } + ] + } + } + }, + + { + type: 'array', + items: [{ + type: 'object', + properties: { + a: { + oneOf: [ + { type: 'boolean' }, + { type: 'null' } + ] + } + } + }] + }, + + { + type: 'object', + properties: { + a: { + not: { + type: 'string' + } + } + } + }, + + { + definitions: { + positiveInteger: { + type: 'integer', + minimum: 0, + exclusiveMinimum: true + } + }, + type: 'object', + properties: { + a: { + type: 'object', + properties: { + b: { + type: 'object', + properties: { + c: { + $ref: '#/definitions/positiveInteger' + } + } + } + } + } + } + }, + + { + type: 'object', + required: ['a', 'b'] + }, + + { + type: 'object', + dependencies: { + a: { + required: ['b'] + } + } + }, + + { + type: 'object', + dependencies: { + a: ['b'] + } + } + ]; + + const data = [ + '123', + { a: 123 }, + [7, 11, 7], + [10, 11, 9], + { a: [{ b: 8 }] }, + 12, + { a: false }, + [{ a: 123 }], + { a: 'abc' }, + { a: { b: { c: 0 } } }, + {}, + { a: 123 }, + { a: 123 } + ]; + + // property: path + { + const expectedPaths = [ + [''], + ['a'], + [''], + ['1'], + ['a.0.b'], + [''], + ['a', 'a'], + ['0.a', '0.a', '0.a'], + ['a'], + ['a.b.c'], + ['a'], + ['b'], + ['b'] + ]; + + let validate: IJsenValidator; + let valid: boolean; + + schemas.forEach((schema, index) => { + validate = jsen(schema); + valid = validate(data[index]); + + console.assert(!valid); + + expectedPaths[index].forEach((path, pindex) => { + try { + console.assert(validate.errors[pindex].path === path); + } + catch (e) { + // console.log(index); + // console.log(validate.errors); + throw e; + } + }); + }); + } + + // property: keyword + { + const expectedKeywords = [ + ['type'], + ['type'], + ['uniqueItems'], + ['maximum'], + ['multipleOf'], + ['maximum'], + ['type', 'type', 'anyOf'], + ['type', 'type', 'oneOf'], + ['not'], + ['exclusiveMinimum'], + ['required'], + ['required'], + ['dependencies'] + ]; + + let validate: IJsenValidator; + let valid: boolean; + + schemas.forEach((schema, index) => { + validate = jsen(schema); + valid = validate(data[index]); + + console.assert(!valid); + + expectedKeywords[index].forEach((keyword, kindex) => { + try { + console.assert(validate.errors[kindex].keyword === keyword); + } + catch (e) { + // console.log(index); + // console.log(validate.errors); + throw e; + } + }); + }); + } + + // adds required property name to path + { + let schema: any = { type: 'object', required: ['a'] }; + let validate = jsen(schema); + let valid = validate({}); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].path === 'a'); + console.assert(validate.errors[0].keyword === 'required'); + + schema = { + type: 'object', + properties: { + a: { + type: 'array', + items: { + type: 'object', + required: ['b'] + } + } + } + }; + + validate = jsen(schema); + valid = validate({ a: [{}] }); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].path === 'a.0.b'); + console.assert(validate.errors[0].keyword === 'required'); + } + + // adds required dependency property to path + { + let schema: any = { + type: 'object', + dependencies: { + a: ['b'] + } + }; + + let validate = jsen(schema); + let valid = validate({ a: 123 }); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].path === 'b'); + console.assert(validate.errors[0].keyword === 'dependencies'); + + schema = { + type: 'object', + properties: { + a: { + type: 'array', + items: { + type: 'object', + dependencies: { + a: ['b'] + } + } + } + } + }; + + validate = jsen(schema); + valid = validate({ a: [{ a: 123 }] }); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].path === 'a.0.b'); + console.assert(validate.errors[0].keyword === 'dependencies'); + } + } + + // multiple errors + { + const schema = { + definitions: { + array: { + maxItems: 1 + } + }, + type: 'object', + properties: { + a: { + anyOf: [ + { items: { type: 'integer' } }, + { $ref: '#/definitions/array' }, + { items: [{ maximum: 3 }] } + ] + } + } + }; + + const data = { a: [Math.PI, Math.E] }; + const validate = jsen(schema); + + // returns multiple errors + { + const valid = validate(data); + + // console.log(validate.errors); + + console.assert(!valid); + console.assert(validate.errors.length === 5); + } + } + + // custom errors + { + const schemas = [ + { + type: 'string', + invalidMessage: 'string is invalid', + requiredMessage: 'string is required' + }, + { + type: 'object', + required: ['a'], + properties: { + a: { + invalidMessage: 'a is invalid', + requiredMessage: 'a is required' + } + } + }, + { + type: 'array', + items: { + type: 'object', + properties: { + a: { + type: 'object', + properties: { + b: { + invalidMessage: 'b is invalid', + requiredMessage: 'b is required' + } + }, + required: ['b'] + } + } + } + }, + { + type: 'object', + properties: { + a: { + type: 'object', + properties: { + c: { + type: 'string', + invalidMessage: 'c is invalid', + requiredMessage: 'c is required' + } + } + } + } + } + ]; + + const data = [ + undefined, + {}, + [{ a: {} }], + { a: { c: 123 } } + ]; + + const expectedMessages = [ + 'string is invalid', + 'a is required', + 'b is required', + 'c is invalid' + ]; + + let validate: IJsenValidator; + let valid: boolean; + + schemas.forEach((schema, index) => { + //it(expectedMessages[index], function () { + validate = jsen(schema); + valid = validate(data[index]); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === expectedMessages[index]); + //}); + }); + } + + // custom keyword messages + { + // uses custom messages on keywords + { + const schemas: any = [ + { + type: 'string', + messages: { type: 'custom message for keyword "type"' } + }, + { + enum: [1, 2, 3], + messages: { enum: 'custom message for keyword "enum"' } + }, + { + minimum: 3, + messages: { minimum: 'custom message for keyword "minimum"' } + }, + { + minimum: 3, + exclusiveMinimum: true, + messages: { exclusiveMinimum: 'custom message for keyword "exclusiveMinimum"' } + }, + { + maximum: 10, + messages: { maximum: 'custom message for keyword "maximum"' } + }, + { + maximum: 10, + exclusiveMaximum: true, + messages: { exclusiveMaximum: 'custom message for keyword "exclusiveMaximum"' } + }, + { + multipleOf: 5, + messages: { multipleOf: 'custom message for keyword "multipleOf"' } + }, + { + minLength: 3, + messages: { minLength: 'custom message for keyword "minLength"' } + }, + { + maxLength: 5, + messages: { maxLength: 'custom message for keyword "maxLength"' } + }, + { + pattern: '\\d+', + messages: { pattern: 'custom message for keyword "pattern"' } + }, + { + format: 'email', + messages: { format: 'custom message for keyword "format"' } + }, + { + minItems: 1, + messages: { minItems: 'custom message for keyword "minItems"' } + }, + { + maxItems: 1, + messages: { maxItems: 'custom message for keyword "maxItems"' } + }, + { + additionalItems: false, + items: [{ type: 'string' }], + messages: { additionalItems: 'custom message for keyword "additionalItems"' } + }, + { + uniqueItems: true, + messages: { uniqueItems: 'custom message for keyword "uniqueItems"' } + }, + { + minProperties: 1, + messages: { minProperties: 'custom message for keyword "minProperties"' } + }, + { + maxProperties: 1, + messages: { maxProperties: 'custom message for keyword "maxProperties"' } + }, + { + required: ['foo'], + messages: { required: 'custom message for keyword "required"' } + }, + { + required: ['foo'], + properties: { + foo: { + messages: { + required: 'custom message for keyword "required"' + } + } + } + }, + { + required: ['foo'], + properties: { + foo: { + messages: { + required: 'this custom message for keyword "required" is assigned' + } + } + }, + messages: { required: 'this custom message for keyword "required" is NOT assigned' } + }, + { + additionalProperties: false, + messages: { additionalProperties: 'custom message for keyword "additionalProperties"' } + }, + { + dependencies: { + foo: ['bar'] + }, + messages: { dependencies: 'custom message for keyword "dependencies"' } + }, + { + anyOf: [ + { type: 'string' }, + { type: 'integer' } + ], + messages: { anyOf: 'custom message for keyword "anyOf"' } + }, + { + oneOf: [ + { type: 'string' }, + { type: 'integer' } + ], + messages: { oneOf: 'custom message for keyword "oneOf"' } + }, + { + not: { + type: 'string' + }, + messages: { not: 'custom message for keyword "not"' } + } + ]; + + const data = [ + 123, + 5, + 1, + 3, + 11, + 10, + 12, + 'ab', + 'abcdef', + 'abc', + 'invalid email', + [], + [1, 2, 3], + ['abc', 'def'], + [1, 2, 2], + {}, + { foo: 1, bar: 2 }, + {}, + {}, + {}, + { foo: 'bar' }, + { foo: 'abc' }, + null, + null, + 'abc' + ]; + + const expectedMessages = [ + schemas[0].messages.type, + schemas[1].messages.enum, + schemas[2].messages.minimum, + schemas[3].messages.exclusiveMinimum, + schemas[4].messages.maximum, + schemas[5].messages.exclusiveMaximum, + schemas[6].messages.multipleOf, + schemas[7].messages.minLength, + schemas[8].messages.maxLength, + schemas[9].messages.pattern, + schemas[10].messages.format, + schemas[11].messages.minItems, + schemas[12].messages.maxItems, + schemas[13].messages.additionalItems, + schemas[14].messages.uniqueItems, + schemas[15].messages.minProperties, + schemas[16].messages.maxProperties, + schemas[17].messages.required, + schemas[18].properties.foo.messages.required, + schemas[19].properties.foo.messages.required, + schemas[20].messages.additionalProperties, + schemas[21].messages.dependencies, + schemas[22].messages.anyOf, + schemas[23].messages.oneOf, + schemas[24].messages.not + ]; + + let validate: IJsenValidator; + let valid: boolean; + + schemas.forEach((schema: any, index: number) => { + validate = jsen(schema); + + valid = validate(data[index]); + + console.assert(!valid); + console.assert(validate.errors[validate.errors.length - 1].message === expectedMessages[index]); + }); + } + + // does not use custom messages on keyword: items (object) + { + const schema = { + items: { + type: 'string', + messages: { + type: 'will be assigned' + } + }, + messages: { + items: 'will not be assigned' + } + }; + + const validate = jsen(schema); + const valid = validate([123]); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === 'will be assigned'); + } + + // does not use custom messages on keyword: items (array) + { + const schema = { + items: [{ + type: 'string', + messages: { + type: 'will be assigned' + } + }], + messages: { + items: 'will not be assigned' + } + }; + + const validate = jsen(schema); + const valid = validate([123, 123]); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === 'will be assigned'); + } + + // does not use custom messages on keyword: properties + { + const schema = { + properties: { + foo: { + type: 'number', + messages: { + type: 'will be assigned' + } + } + }, + messages: { + properties: 'will not be assigned' + } + }; + + const validate = jsen(schema); + const valid = validate({ foo: 'bar' }); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === 'will be assigned'); + } + + // does not use custom messages on keyword: patternProperties + { + const schema = { + patternProperties: { + '^foo$': { + type: 'number', + messages: { + type: 'will be assigned' + } + } + }, + messages: { + patternProperties: 'will not be assigned' + } + }; + + const validate = jsen(schema); + const valid = validate({ foo: 'bar' }); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === 'will be assigned'); + } + + // does not use custom messages on keyword: dependencies (schema) + { + const schema = { + dependencies: { + foo: { + minProperties: 2, + messages: { + minProperties: 'will be assigned' + } + } + }, + messages: { + dependencies: 'will not be assigned' + } + }; + + const validate = jsen(schema); + const valid = validate({ foo: 'bar' }); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === 'will be assigned'); + } + + // does not use custom messages on keyword: allOf + { + const schema = { + dependencies: { + foo: { + minProperties: 2, + messages: { + minProperties: 'will be assigned' + } + } + }, + allOf: [ + { + minimum: 2, + messages: { + minimum: 'will not be assigned' + } + }, + { + maximum: 5, + messages: { + maximum: 'will be assigned' + } + } + ], + messages: { + allOf: 'will not be assigned' + } + }; + + const validate = jsen(schema); + const valid = validate(6); + + console.assert(!valid); + console.assert(validate.errors.length === 1); + console.assert(validate.errors[0].message === 'will be assigned'); + } + } +} + +const doesThrow = (func: Function) => { + try { + func(); + } + catch (e) { + return true; + } + + return false; +}; + +const doesNotThrow = (func: Function) => { + return !doesThrow(func); +}; + +// fixes +{ + // Fix broken inlining of regular expressions containing slashes (#15, #25) + { + const schema = { + type: 'string', + pattern: '^/dev/[^/]+(/[^/]+)*$' + }; + + console.assert(doesNotThrow(jsen(schema))); + } + + // Fix code generation breaks when object properties in schema are not valid identifiers (#16) + { + const schema = { + type: 'object', + properties: { + 123: { + type: 'boolean' + } + } + }; + + let validate: IJsenValidator; + + console.assert(doesNotThrow(() => { + validate = jsen(schema); + }) + ); + + console.assert(validate({ 123: true })); + } + + // Fix cannot dereference schema when ids change resolution scope (#14) + { + let schema: any = { + $ref: '#child', + definitions: { + child: { + id: '#child', + type: 'string' + } + } + }; + + let validate: IJsenValidator; + + console.assert(doesNotThrow(() => { + validate = jsen(schema); + }) + ); + + console.assert(validate('abc')); + console.assert(!validate(123)); + + schema = { + $ref: '#child/definitions/subchild', + definitions: { + child: { + id: '#child', + definitions: { + subchild: { + type: 'number' + } + } + } + } + }; + + console.assert(doesThrow(() => { + validate = jsen(schema); + }) + ); + } + + // Fix recursive calls to the same cached $ref validator resets the error object + { + const schema = { + type: 'array', + items: { + type: 'object', + properties: { + foo: { $ref: '#' } + }, + required: ['foo'] + } + }; + + const validate = jsen(schema); + + console.assert(validate([{ foo: [] }])); + console.assert(validate([{ foo: [{ foo: [] }] }])); + console.assert(!validate([{ bar: [] }])); + console.assert(!validate([{ foo: [{ foo: [] }, { bar: [] }] }])); // Bug! False positive + } +} + +// format +{ + // date-time + { + const schema = { format: 'date-time' }; + const validate = jsen(schema); + + console.assert(validate(new Date().toJSON())); + + console.assert(!validate('')); + console.assert(!validate(new Date().toUTCString())); + console.assert(!validate(new Date().toLocaleDateString())); + console.assert(!validate(new Date().toTimeString())); + } + + // uri + { + const schema = { format: 'uri' }; + const validate = jsen(schema); + + console.assert(validate('http://google.com')); + console.assert(validate('ftp://my-site')); + console.assert(validate('custom://my-site/long/$cr@mbl3d/u_r-l?with=query%20string')); + console.assert(validate('//no-scheme-here')); + + console.assert(!validate('')); + console.assert(!validate('google')); + console.assert(!validate('/google')); + console.assert(!validate('://google')); + console.assert(!validate('http://google.com/no space allowed')); + } + + // email + { + const schema = { format: 'email' }; + const validate = jsen(schema); + const maxLongHostname1 = new Array(5).join('.' + new Array(64).join('a')).substr(1); // 255 chars (4 groups x 63 chars) + const maxLongHostname2 = new Array(9).join('.' + new Array(32).join('a')).substr(1); // 255 chars (8 groups x 31 chars) + + console.assert(validate('me@domain')); + console.assert(validate('first.last+plus-dash#hash!bang$dollar%percent&\'quote*star/dash=equal?question^pow_under`backtick{brace}|bar~tilde@domain')); + console.assert(validate('me@domain.with.multiple.subdomains')); + console.assert(validate('me@domain-parts.may.contain-dashes')); + console.assert(validate('me@a-single-domain-part-can-be-up-to-sixty-three-characters-long63')); + console.assert(validate('me@' + maxLongHostname1)); + console.assert(validate('me@' + maxLongHostname2)); + + console.assert(!validate('')); + console.assert(!validate('qu"ote\'s@domain')); + console.assert(!validate('me@no_underscores+or?special$chars')); + console.assert(!validate('me@ends-with-dash-')); + console.assert(!validate('me@-starts-with-dash')); + console.assert(!validate('me@asingle-domain-part-cannot-be-longer-than-sixty-three-characters')); + + // These verify that a hostname cannot be longer than 255 chars in total. However, + // maximum string length verification cannot be performed in the same regex, so + // these test cases fail. Users must additionall use the `maxlength` keyword in this case. + // assert(!validate('me@' + maxLongHostname1 + '.a')); + // assert(!validate('me@' + maxLongHostname2 + '.a')); + } + + // ipv4 + { + const schema = { format: 'ipv4' }; + const validate = jsen(schema); + + console.assert(validate('0.0.0.0')); + console.assert(validate('255.255.255.255')); + console.assert(validate('127.0.0.1')); + + console.assert(!validate('')); + console.assert(!validate('...')); + console.assert(!validate('0.0.0.-1')); + console.assert(!validate('0.0.-1.0')); + console.assert(!validate('0.-1.0.0')); + console.assert(!validate('-1.0.0.0')); + console.assert(!validate('256.0.0.0')); + console.assert(!validate('0.256.0.0')); + console.assert(!validate('0.0.256.0')); + console.assert(!validate('0.0.0.256')); + } + + // ipv6 + { + const schema = { format: 'ipv6' }; + const validate = jsen(schema); + + console.assert(validate('1:2:3:4:5:6:7:8')); + console.assert(validate('1::')); + console.assert(validate('1:2:3:4:5:6:7::')); + console.assert(validate('1::8')); + console.assert(validate('1:2:3:4:5:6::8')); + console.assert(validate('1::7:8')); + console.assert(validate('1:2:3:4:5::7:8')); + console.assert(validate('1:2:3:4:5::8')); + console.assert(validate('1::6:7:8')); + console.assert(validate('1:2:3:4::6:7:8')); + console.assert(validate('1:2:3:4::8')); + console.assert(validate('1::5:6:7:8')); + console.assert(validate('1:2:3::5:6:7:8')); + console.assert(validate('1:2:3::8')); + console.assert(validate('1::4:5:6:7:8')); + console.assert(validate('1:2::4:5:6:7:8')); + console.assert(validate('1:2::8')); + console.assert(validate('1::3:4:5:6:7:8')); + console.assert(validate('1::8')); + console.assert(validate('::2:3:4:5:6:7:8')); + console.assert(validate('::8')); + console.assert(validate('::')); + + // link-local IPv6 addresses with zone index + console.assert(validate('fe80::7:8%eth0')); + console.assert(validate('fe80::7:8%1')); + + // IPv4-mapped IPv6 addresses and IPv4-translated addresses + console.assert(validate('::255.255.255.255')); + console.assert(validate('::ffff:255.255.255.255')); + console.assert(validate('::ffff:0:255.255.255.255')); + + // IPv4-Embedded IPv6 Address + console.assert(validate('2001:db8:3:4::192.0.2.33')); + console.assert(validate('64:ff9b::192.0.2.33')); + + console.assert(!validate('')); + console.assert(!validate('::_')); + + // TODO: we may need more invalid cases here + } + + // hostname + { + const schema = { format: 'hostname' }, + validate = jsen(schema), + maxLong1 = new Array(5).join('.' + new Array(64).join('a')).substr(1), // 255 chars (4 groups x 63 chars) + maxLong2 = new Array(9).join('.' + new Array(32).join('a')).substr(1); // 255 chars (8 groups x 31 chars) + + console.assert(validate('my.host')); + console.assert(validate('host')); + console.assert(validate('domain.with.multiple.subdomains')); + console.assert(validate('domain-parts.may.contain-dashes')); + console.assert(validate('a-single-domain-part-can-be-up-to-sixty-three-characters-long63')); + console.assert(validate(maxLong1)); + console.assert(validate(maxLong2)); + + console.assert(!validate('')); + console.assert(!validate('me@domain')); + console.assert(!validate('qu"ote\'s')); + console.assert(!validate('no_underscores+or?special$chars')); + console.assert(!validate('ends-with-dash-')); + console.assert(!validate('-starts-with-dash')); + console.assert(!validate('asingle-domain-part-cannot-be-longer-than-sixty-three-characters')); + + // These verify that a hostname cannot be longer than 255 chars in total. However, + // maximum string length verification cannot be performed in the same regex, so + // these test cases fail. Users must additionall use the `maxlength` keyword in this case. + // assert(!validate(maxLong1 + '.a')); + // assert(!validate(maxLong2 + '.a')); + } + + // custom format + { + // accepts string + { + const schema = { format: 'custom' }, + custom = '^\\d+$', + validate = jsen(schema, { + formats: { + custom: custom + } + }); + + console.assert(validate('123')); + console.assert(!validate('a123')); + } + + // accepts regex + { + const schema = { format: 'custom' }, + custom = /^\d+$/, + validate = jsen(schema, { + formats: { + custom: custom + } + }); + + console.assert(validate('123')); + console.assert(!validate('a123')); + } + + // accepts function + { + let schema = { format: 'custom' }, + callCount = 0, + custom = (value: any, childSchema: any) => { + console.assert(value.indexOf('123') > -1); + console.assert(childSchema === schema); + + callCount++; + + return /^\d+$/.test(value); + }, + validate = jsen(schema, { + formats: { + custom: custom + } + }); + + console.assert(validate('123')); + console.assert(!validate('a123')); + console.assert(callCount === 2); + } + + // is run for all types + { + let schema = { format: 'custom' }, + callCount = 0, + options = { + formats: { + custom: () => { + callCount++; + return true; + } + } + }, + validate = jsen(schema, options), + data = [ + undefined, + null, + 'abc', + 123, + Math.PI, + true, + false, + {}, + [], + new Date() + ]; + + data.forEach((dataItem) => { + validate(dataItem); + console.assert(callCount === 1); + callCount = 0; + }); + } + + // is not run if a built-in keyword fails + { + let schema = { + format: 'custom', + type: 'number', + maximum: 10 + }, + callCount = 0, + options = { + formats: { + custom: () => { + callCount++; + return true; + } + } + }, + validate = jsen(schema, options); + + console.assert(!validate(123)); + console.assert(callCount === 0); + + console.assert(validate(7)); + console.assert(callCount === 1); + } + + // common scenarios + { + // verify passwords match + { + let schema = { + description: 'User account creation form', + type: 'object', + properties: { + password: { + type: 'string', + minLength: 8 + }, + password_confirm: { + type: 'string', + minLength: 8 + } + }, + format: 'passwordsMatch' + }, + options = { + formats: { + passwordsMatch: (obj: any) => { + callCount++; + return obj.password === obj.password_confirm; + } + } + }, + data = { + password: '1234567', + password_confirm: '1234567' + }, + validate = jsen(schema, options), + callCount = 0; + + console.assert(!validate(data)); // minLength validator failed + console.assert(callCount === 0); + + data.password += '8'; + data.password_confirm += '9'; + + console.assert(!validate(data)); // custom validator failed + console.assert(callCount === 1); + + data.password_confirm = data.password; + + console.assert(validate(data)); // OK + console.assert(callCount === 2); + } + } + } +} + +// option: greedy +{ + // validates as many keywords as possible + { + let schema = { + type: 'object', + properties: { + test1: { + type: 'string' + }, + test2: { + type: 'object', + properties: { + test21: { + type: 'number' + } + } + }, + test3: { + type: 'number' + }, + test4: { $ref: '#external' } + }, + additionalProperties: false + }, + options = { + greedy: true, + schemas: { + external: { + type: 'string' + } + } + }, + validate = jsen(schema, options), + invalidTest = { + test1: 1, + test2: '2', + test3: 'j', + test4: 4 + }, + ret = validate(invalidTest); + + console.assert(!ret); // false + console.assert(JSON.stringify(validate.errors) + === JSON.stringify([ + { path: 'test1', keyword: 'type' }, + { path: 'test2', keyword: 'type' }, + { path: 'test3', keyword: 'type' }, + { path: 'test4', keyword: 'type' } + ]) + ); + + delete options.greedy; + + validate = jsen(schema, options); + + ret = validate(invalidTest); + + console.assert(!ret); // false + console.assert(JSON.stringify(validate.errors) + === JSON.stringify([{ path: 'test1', keyword: 'type' }]) + ); + } + + // does not descend into invalid objects + { + let schema = { + type: 'object', + properties: { + test1: { type: 'object' }, + test2: { + required: ['foo'] + }, + test3: { + properties: { + foo: { type: 'string' } + } + }, + test4: { + type: 'array', + items: { + type: 'object', + required: ['foo'] + } + } + } + }, + options = { greedy: true }, + data = { + test1: 123, + test2: {}, + test3: 123, + test4: [{}, { foo: 123 }, null] + }, + validate = jsen(schema, options), + ret = validate(data); + + console.assert(!ret); + console.assert(JSON.stringify(validate.errors) + === JSON.stringify([ + { path: 'test1', keyword: 'type' }, + { path: 'test2.foo', keyword: 'required' }, + { path: 'test4.0.foo', keyword: 'required' }, + { path: 'test4.2', keyword: 'type' } + ]) + ); + } +} + +// jsen +{ + // is a function + { + console.assert(typeof jsen === "function"); + } + + // throws if schema is not an object + { + console.assert(doesThrow(jsen())); + console.assert(doesThrow(jsen(null))); + console.assert(doesThrow(jsen(false))); + console.assert(doesThrow(jsen(123))); + console.assert(doesThrow(jsen("abc"))); + console.assert(doesThrow(jsen([]))); + console.assert(doesNotThrow(jsen({}))); + } + + // produces a function + { + const validate = jsen({}); + console.assert(typeof validate === 'function'); + console.assert(validate() === true); + // console.assert(validate.error === null); + } +} + +// type: integer +{ + // required + { + const schema = { type: 'integer' }, + validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + console.assert(validate(123)); + } + + // nullable + { + const schema = { type: ['integer', 'null'] }, + validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(null)); + console.assert(validate(123)); + } + + // type + { + const schema = { type: 'integer' }, + validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate(true)); + console.assert(!validate(false)); + console.assert(!validate([])); + console.assert(!validate({})); + console.assert(!validate(Math.PI)); + + console.assert(validate(13)); + } + + // enum + { + const schema = { type: 'integer', enum: [1, 3, 5, 7] }, + validate = jsen(schema); + + console.assert(!validate(4)); + console.assert(validate(5)); + } + + // minimum + { + const schema = { type: 'integer', minimum: 7 }, + validate = jsen(schema); + + console.assert(!validate(6)); + + console.assert(validate(7)); + console.assert(validate(999)); + } + + // exclusiveMinimum + { + const schema = { + type: 'integer', + minimum: 7, + exclusiveMinimum: true + }, + validate = jsen(schema); + + console.assert(!validate(6)); + console.assert(!validate(7)); + + console.assert(validate(8)); + console.assert(validate(999)); + } + + // maximum + { + const schema = { type: 'integer', maximum: 77 }, + validate = jsen(schema); + + console.assert(!validate(78)); + + console.assert(validate(-12)); + console.assert(validate(76)); + console.assert(validate(77)); + } + + // exclusiveMaximum + { + const schema = { + type: 'integer', + maximum: 77, + exclusiveMaximum: true + }, + validate = jsen(schema); + + console.assert(!validate(77)); + console.assert(!validate(78)); + + console.assert(validate(-12)); + console.assert(validate(75)); + console.assert(validate(76)); + } + + // multipleOf + { + const schema = { type: 'integer', multipleOf: 7 }, + validate = jsen(schema); + + console.assert(!validate(8)); + + console.assert(validate(14)); + console.assert(validate(-49)); + console.assert(validate(77)); + } +} + +// missing $ref +{ + // passes validation with ignore missing $ref + { + let schema = { + type: 'object', + properties: { + test1: { $ref: '#external1' }, + test2: { + type: 'number' + }, + test3: { $ref: '#external3' } //missing + }, + additionalProperties: false + }, + external1 = { + type: 'object', + properties: { + test11: { $ref: '#external11' }, //missing + test12: { + type: 'number' + }, + test13: { $ref: '#external11' } //duplicate + } + }, + validate = jsen(schema, { + schemas: { + external1: external1 + }, + missing$Ref: true + }), + missingTest = { + test1: { + test11: 'missing', + test12: 5, + test13: 'missing too' + }, + test2: 2, + test3: 3 + }, + invalidTest = { + test1: { + test11: 'missing', + test12: 5, + test13: 'missing too' + }, + test2: 'fail', + test3: 3 + }, + ret: boolean; + + ret = validate(missingTest); + console.assert(ret); // true + + ret = validate(invalidTest); + console.assert(!ret); // !false + } +} + +// multi schema +{ + // allOf + { + const schema = { + allOf: [ + { type: 'number' }, + { type: 'integer' } + ] + }, + validate = jsen(schema); + + console.assert(!validate(null)); + console.assert(!validate(Math.PI)); + + console.assert(validate(0)); + console.assert(validate(777)); + console.assert(validate(-9)); + } + + // anyOf + { + const schema = { + anyOf: [ + { type: 'string' }, + { type: 'number' } + ] + }, + validate = jsen(schema); + + console.assert(!validate(null)); + console.assert(!validate(true)); + console.assert(!validate({})); + console.assert(!validate([])); + + console.assert(validate('abc')); + console.assert(validate(123)); + console.assert(validate('')); + console.assert(validate(0)); + } + + // oneOf + { + const schema = { + oneOf: [ + { type: 'number', maximum: 5 }, + { type: 'number', minimum: 3 } + ] + }, + validate = jsen(schema); + + console.assert(!validate(null)); + console.assert(!validate(true)); + console.assert(!validate({})); + console.assert(!validate([])); + // matches both validators + console.assert(!validate(3)); + + console.assert(validate(0)); + console.assert(validate(1)); + console.assert(validate(2)); + console.assert(validate(6)); + console.assert(validate(17)); + } + + // not + { + const schema = { + not: { + type: 'array' + } + }, + validate = jsen(schema); + + console.assert(!validate([])); + + console.assert(validate(0)); + console.assert(validate(false)); + console.assert(validate('abc')); + console.assert(validate({})); + console.assert(validate(null)); + console.assert(validate()); + } +} + +// type: null +{ + // required + { + const schema = { type: 'null' }, + validate = jsen(schema); + + console.assert(!validate(undefined)); + console.assert(validate(null)); + } + + // type + { + const schema = { type: 'null' }, + validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate([])); + console.assert(!validate({})); + console.assert(!validate(Math.PI)); + + console.assert(validate(null)); + } +} + +// type: number +{ + // required + { + const schema = { type: 'number' }, + validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + + console.assert(validate(Math.PI)); + console.assert(validate(123)); + } + + // nullable + { + const schema = { type: ['number', 'null'] }, + validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(null)); + console.assert(validate(Math.PI)); + } + + // type + { + const schema = { type: 'number' }, + validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate(true)); + console.assert(!validate(false)); + console.assert(!validate([])); + console.assert(!validate({})); + + console.assert(validate(13)); + console.assert(validate(17.8)); + console.assert(validate(Math.PI)); + } + + // enum + { + const schema = { + type: 'number', + enum: [1, Math.E, 3, 5, 7] + }, + validate = jsen(schema); + + console.assert(!validate(4)); + console.assert(!validate(Math.PI)); + + console.assert(validate(5)); + console.assert(validate(Math.E)); + } + + // minimum + { + const schema = { type: 'number', minimum: 7 }, + validate = jsen(schema); + + console.assert(!validate(6)); + console.assert(!validate(Math.PI)); + + console.assert(validate(7)); + console.assert(validate(999)); + } + + // exclusiveMinimum + { + const schema = { + type: 'number', + minimum: 7, + exclusiveMinimum: true + }, + validate = jsen(schema); + + console.assert(!validate(6)); + console.assert(!validate(7)); + console.assert(!validate(Math.PI)); + + console.assert(validate(8)); + console.assert(validate(999)); + } + + // maximum + { + const schema = { type: 'number', maximum: 77 }, + validate = jsen(schema); + + console.assert(!validate(77.000001)); + console.assert(!validate(78)); + + console.assert(validate(-12)); + console.assert(validate(76)); + console.assert(validate(77)); + console.assert(validate(Math.PI)); + } + + // exclusiveMaximum + { + const schema = { + type: 'number', + maximum: 77, + exclusiveMaximum: true + }, + validate = jsen(schema); + + console.assert(!validate(77)); + console.assert(!validate(78)); + + console.assert(validate(-12)); + console.assert(validate(75)); + console.assert(validate(76)); + console.assert(validate(76.99999)); + } + + // multipleOf + { + let schema = { type: 'number', multipleOf: 7 }, + validate = jsen(schema); + + console.assert(!validate(8)); + + console.assert(validate(14)); + console.assert(validate(-49)); + console.assert(validate(77)); + + schema = { + type: 'number', + multipleOf: 3.14 // Math.PI + }; + + validate = jsen(schema); + + console.assert(!validate(2.5)); + + console.assert(validate(9.42)); // 3 * Math.PI + } + + // fix multipleOf doesn't validate data for decimal point (#1) + { + const schema = { type: 'number', multipleOf: 0.01 }, + validate = jsen(schema); + + console.assert(validate(18.15)); + } +} + +// type: object +{ + // required + { + const schema = { type: 'object' }, + validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + + console.assert(validate({})); + } + + // nullable + { + const schema = { type: ['object', 'null'] }, + validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(null)); + console.assert(validate({})); + } + + // type + { + const schema = { type: 'object' }, + validate = jsen(schema); + + console.assert(!validate('123')); + console.assert(!validate(false)); + console.assert(!validate([])); + console.assert(!validate(Math.PI)); + + console.assert(validate({})); + console.assert(jsen({ type: 'object', properties: {} }, {})()); + } + + // maxProperties + { + const schema = { type: 'object', maxProperties: 3 }, + validate = jsen(schema); + + console.assert(!validate({ a: 1, b: 2, c: 3, d: 4 })); + + console.assert(validate({})); + console.assert(validate({ a: 1 })); + console.assert(validate({ a: 1, b: 2 })); + console.assert(validate({ a: 1, b: 2, c: 3 })); + } + + // minProperties + { + const schema = { type: 'object', minProperties: 2 }, + validate = jsen(schema); + + console.assert(!validate({})); + console.assert(!validate({ a: 1 })); + + console.assert(validate({ a: 1, b: 2 })); + console.assert(validate({ a: 1, b: 2, c: 3 })); + } + + // required properties + { + const schema = { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' }, + c: { type: 'boolean' } + }, + required: ['a', 'b'] + }, + validate = jsen(schema); + + console.assert(!validate({})); + console.assert(!validate({ c: true })); + console.assert(!validate({ a: 'abc', c: true })); + console.assert(!validate({ b: 123, c: true })); + console.assert(!validate({ a: 'abc', b: undefined })); + + console.assert(validate({ a: 'abc', b: 123 })); + console.assert(validate({ a: 'abc', b: 123, c: true })); + } + + // additionalProperties + { + let schema = { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' } + }, + additionalProperties: true + }, + validate = jsen(schema); + + console.assert(validate({ a: 'abc' })); + console.assert(validate({ b: 123 })); + console.assert(validate({ a: 'abc', b: 123 })); + console.assert(validate({ a: 'abc', b: 123, c: true })); + + schema.additionalProperties = false; + validate = jsen(schema); + + console.assert(!validate({ c: true })); + console.assert(!validate({ a: 'abc', b: 123, c: true })); + + console.assert(validate({ a: 'abc', b: 123 })); + console.assert(jsen({ type: 'object', additionalProperties: false })({})); + } + + // additionalProperties as schema + { + const schema = { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' } + }, + additionalProperties: { + type: 'boolean' + } + }, + validate = jsen(schema); + + console.assert(!validate({ a: 'abc', b: 123, c: 123 })); + + console.assert(validate({ a: 'abc', b: 123, c: false })); + } + + // additionalProperties with patternProperties + { + let schema = { + type: 'object', + properties: { + a: { type: 'string' } + }, + patternProperties: { + '^b': { type: 'number' } + }, + additionalProperties: true + }, + validate = jsen(schema); + + console.assert(validate({ a: 'abc' })); + console.assert(validate({ b: 123 })); + console.assert(validate({ a: 'abc', b: 123, bar: Math.E, baz: Math.PI })); + console.assert(validate({ a: 'abc', baz: 123, c: true })); + + schema.additionalProperties = false; + validate = jsen(schema); + + console.assert(!validate({ c: true })); + console.assert(!validate({ a: 'abc', bar: 123, c: true })); + + console.assert(validate({ a: 'abc', baz: 123 })); + console.assert(jsen({ type: 'object', additionalProperties: false })({})); + } + + // patternProperties + { + const schema = { + type: 'object', + patternProperties: { + '^a': { type: 'string' }, + '^b': { type: 'number' } + } + }, + validate = jsen(schema); + + console.assert(!validate({ a: 123 })); + console.assert(!validate({ b: 'abc' })); + + console.assert(validate({})); + console.assert(validate({ a: 'abc' })); + console.assert(validate({ b: 123 })); + console.assert(validate({ a: 'abc', b: 123 })); + } + + // dependencies: schema + { + const schema = { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' } + }, + dependencies: { + a: { + type: 'object', + required: ['c'], + properties: { + c: { type: 'boolean' } + } + }, + b: { + type: 'object', + required: ['f'], + properties: { + f: { type: 'null' } + } + }, + g: { + type: 'object', + required: ['b'], + properties: { + b: { + type: 'integer' + } + } + } + } + }, + validate = jsen(schema); + + console.assert(!validate({ a: 'abc' })); + console.assert(!validate({ a: 'abc', c: 123 })); + console.assert(!validate({ b: Math.PI, f: false })); + console.assert(!validate({ b: Math.PI, g: null })); + + console.assert(validate({})); + console.assert(validate({ a: 'abc', c: false })); + console.assert(validate({ b: Math.PI, f: null })); + console.assert(validate({ b: 123, g: 'any value', f: null })); + } + + // dependencies: property + { + const schema = { + type: 'object', + properties: { + a: { type: 'string' }, + b: { type: 'number' }, + c: { type: 'boolean' } + }, + dependencies: { + a: ['b', 'c'] + } + }, + validate = jsen(schema); + + console.assert(!validate({ a: 'abc' })); + console.assert(!validate({ a: 'abc', b: 123 })); + + console.assert(validate({})); + console.assert(validate({ a: 'abc', b: 123, c: false })); + } + + // nested graph + { + const schema = { + type: ['object', 'null'], + properties: { + a: { type: 'string' }, + b: { type: 'number' }, + c: { + type: 'array', + items: { type: 'boolean' } + } + }, + required: ['a'] + }, + validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate({})); + console.assert(!validate({ a: 123 })); + console.assert(!validate({ a: 'abc', b: false })); + console.assert(!validate({ a: 'abc', c: [null] })); + + console.assert(validate(null)); + console.assert(validate({ a: 'abc', b: 123.4, c: [true, false] })); + console.assert(validate({ a: 'abc', b: 0 })); + console.assert(validate({ a: 'abc', c: [true, false] })); + console.assert(validate({ a: 'abc', c: [] })); + } +} + +// $ref +{ + // throws if string is not in correct format + { + console.assert(doesThrow( + jsen({ $ref: '' }) + )); + + console.assert(doesThrow( + jsen({ $ref: '#double//slash' }) + )); + + console.assert(doesThrow( + jsen({ $ref: '#ends/with/slash/' }) + )); + + console.assert(doesThrow( + // invalid reference, non-existent schema properties + jsen({ $ref: '#a/b/c' }) + )); + + console.assert(doesNotThrow( + // schema resolves to itself + jsen({ $ref: '#' }) + )); + + console.assert(doesNotThrow( + jsen({ + a: { + b: { + c: { + type: 'any' + } + } + }, + $ref: '#/a/b/c' + }) + )); + + console.assert(doesNotThrow( + jsen({ + arr: [ + { value: { type: 'string' } }, + { value: { type: 'number' } }, + { value: { type: 'boolean' } } + ], + type: 'object', + properties: { + a: { $ref: '#arr/2/value' } + } + }) + )); + } + + // external schema + { + // finds external schema with a hash + { + const external = { type: 'string' }, + schema = { $ref: '#external' }, + validate = jsen(schema, { + schemas: { + external: external + } + }); + + console.assert(validate('abc')); + console.assert(!validate(123)); + } + + // finds external schema without a hash + { + const external = { type: 'string' }, + schema = { $ref: 'external' }, + validate = jsen(schema, { + schemas: { + external: external + } + }); + + console.assert(validate('abc')); + console.assert(!validate(123)); + } + + // throws when no external schema found + { + const schema = { $ref: '#external' }; + + console.assert(doesNotThrow( + jsen(schema) + )); + } + + // own property takes precendence over external schema + { + const external = { type: 'string' }, + schema = { + external: { type: 'number' }, + $ref: '#external' + }, + validate = jsen(schema, { + schemas: { + external: external + } + }); + + console.assert(!validate('abc')); + console.assert(validate(123)); + } + + // external schemas have their own dereferencing scope + { + const external = { + inner: { type: 'string' }, + $ref: '#inner' + }, + schema = { + inner: { type: 'number' }, + $ref: '#external' + }, + validate = jsen(schema, { + schemas: { + external: external + } + }); + + console.assert(validate('abc')); + console.assert(!validate(123)); + } + } +} + +// type: string +{ + // required + { + const schema = { type: 'string' }, + validate = jsen(schema); + + console.assert(!validate()); + console.assert(!validate(null)); + + console.assert(validate('abc')); + } + + // nullable + { + const schema = { type: ['string', 'null'] }, + validate = jsen(schema); + + console.assert(!validate(undefined)); + + console.assert(validate(null)); + console.assert(validate('')); + } + + // type + { + const schema = { type: 'string' }, + validate = jsen(schema); + + console.assert(!validate(123)); + console.assert(!validate(true)); + console.assert(!validate(false)); + console.assert(!validate(0)); + console.assert(!validate([])); + console.assert(!validate({})); + + console.assert(validate('abc')); + } + + // enum + { + const schema = { type: 'string', enum: ['a', 'b', 'c'] }, + validate = jsen(schema); + + console.assert(!validate('not in enum')); + console.assert(validate('b')); + } + + // minLength + { + const schema = { type: 'string', minLength: 10 }, + validate = jsen(schema); + + console.assert(!validate('too short')); + console.assert(validate('just long enough')); + } + + // maxLength + { + const schema = { type: 'string', maxLength: 12 }, + validate = jsen(schema); + + console.assert(!validate('this string is too long')); + console.assert(validate('short enough')); + } + + // pattern + { + let schema: any = { type: 'string', pattern: '\\d' }, + validate = jsen(schema); + + console.assert(!validate('a')); + console.assert(validate('1')); + + schema = { type: 'string', pattern: /\d/ }; + validate = jsen(schema); + + console.assert(!validate('a')); + console.assert(validate('1')); + } +} + +// unique +{ + // filters unique values + { + const inputs = [ + [1, 'a', 3, false, null, undefined], + ['abc', 123, true, 123, false, Math.PI, 'abc', true, null, null] + ], + expected = [ + [1, 'a', 3, false, null, undefined], + ['abc', 123, true, false, Math.PI, null] + ]; + + for (let i = 0; i < inputs.length; i++) { + console.assert(JSON.stringify(jsen.unique(inputs[i])) === JSON.stringify(expected[i])); + } + } + + // performs deep equality checks + { + const input: any = [ + {}, + { a: 1 }, + { b: { c: { d: 123, f: null }, e: 'abc' } }, + [1, 2, 3], + [{ a: 213 }], + { b: 1 }, + { a: 1, b: undefined }, + { b: { e: 'abc', c: { f: null, d: 123 } } }, + [1, 2, 3], + [{ a: 213 }] + ], + expected: any = [ + {}, + { a: 1 }, + { b: { c: { d: 123, f: null }, e: 'abc' } }, + [1, 2, 3], + [{ a: 213 }], + { b: 1 }, + { a: 1, b: undefined } + ]; + + console.assert(JSON.stringify(jsen.unique(input)) === JSON.stringify(expected)); + } + + // unique.findIndex + { + // finds an item index with comparator + { + const arr = [{}, { a: 1 }, { a: 1, b: 2 }], + expected = 2, + comparator = (obj1: any, obj2: any) => { + return obj1.a === obj2.a && obj1.b === obj2.b; + }; + + console.assert(jsen.unique.findIndex(arr, { a: 1, b: 2 }, comparator) === expected); + } + + // returns -1 when item cannot be found + { + const arr = [{}, { a: 1 }, { a: 1, b: 2 }], + expected = -1, + comparator = (obj1: any, obj2: any) => { + return obj1.a === obj2.a && obj1.b === obj2.b; + }; + + console.assert(jsen.unique.findIndex(arr, { a: 1, b: null }, comparator) === expected); + } + } +} diff --git a/jsen/jsen.d.ts b/jsen/jsen.d.ts new file mode 100644 index 000000000..709ebe1ea --- /dev/null +++ b/jsen/jsen.d.ts @@ -0,0 +1,42 @@ +// Type definitions for jsen (JSON Sentinel) +// Project: https://github.com/bugventure/jsen +// Definitions by: Vladimir Đokić +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IJsenFormats { + [key: string]: string | RegExp | Function; +} + +interface IJSenSettings { + missing$Ref?: boolean; + greedy?: boolean; + copy?: boolean; + additionalProperties?: boolean; + formats?: IJsenFormats; + schemas?: any; +} + +interface IJsenValidator { + (data?: any): boolean; + build(initial?: any, options?: any): any; + errors?: IValidateError[]; +} + +interface IValidateError { + path: string; + keyword: string; + message?: string; +} + +interface IJsenUnique { + (array: any[]): boolean; + findIndex(array: any[], value: any, comparator: (obj1: any, obj2: any) => boolean): number; +} +interface IJsen { + (schema?: any, options?: IJSenSettings): IJsenValidator; + clone(data: any): any; + equal(a: any, b: any): boolean; + unique: IJsenUnique; +} + +declare var jsen: IJsen; From ca8123463a34ec4090f77287104498403291d15f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladimir=20=C4=90oki=C4=87?= Date: Thu, 24 Mar 2016 17:29:26 +0100 Subject: [PATCH 10/53] Add IJsenBuildSettings interface (specific to build(...) method) that extends IJsenSettings. Make errors property in IJsenValidator not nullable. --- jsen/jsen.d.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/jsen/jsen.d.ts b/jsen/jsen.d.ts index 709ebe1ea..b70fdfd95 100644 --- a/jsen/jsen.d.ts +++ b/jsen/jsen.d.ts @@ -10,16 +10,19 @@ interface IJsenFormats { interface IJSenSettings { missing$Ref?: boolean; greedy?: boolean; - copy?: boolean; - additionalProperties?: boolean; formats?: IJsenFormats; schemas?: any; } +interface IJsenBuildSettings extends IJSenSettings { + copy?: boolean; + additionalProperties?: boolean; +} + interface IJsenValidator { (data?: any): boolean; - build(initial?: any, options?: any): any; - errors?: IValidateError[]; + build(initial?: any, options?: IJsenBuildSettings): any; + errors: IValidateError[]; } interface IValidateError { From f48aabd23b1088ee67d02c18c1d181b31f094800 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladimir=20=C4=90oki=C4=87?= Date: Thu, 24 Mar 2016 17:53:40 +0100 Subject: [PATCH 11/53] Remove inheritance between IJsenBuildSettings and IJsenSettings. Fix naming case for the interface so that is consistent. --- jsen/jsen-tests.ts | 6 +++--- jsen/jsen.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/jsen/jsen-tests.ts b/jsen/jsen-tests.ts index 8504c0279..54dbd8ae9 100644 --- a/jsen/jsen-tests.ts +++ b/jsen/jsen-tests.ts @@ -2261,7 +2261,7 @@ const doesNotThrow = (func: Function) => { { let schema = { format: 'custom' }, callCount = 0, - options = { + options = { formats: { custom: () => { callCount++; @@ -2298,7 +2298,7 @@ const doesNotThrow = (func: Function) => { maximum: 10 }, callCount = 0, - options = { + options = { formats: { custom: () => { callCount++; @@ -2334,7 +2334,7 @@ const doesNotThrow = (func: Function) => { }, format: 'passwordsMatch' }, - options = { + options = { formats: { passwordsMatch: (obj: any) => { callCount++; diff --git a/jsen/jsen.d.ts b/jsen/jsen.d.ts index b70fdfd95..e230818b8 100644 --- a/jsen/jsen.d.ts +++ b/jsen/jsen.d.ts @@ -7,14 +7,14 @@ interface IJsenFormats { [key: string]: string | RegExp | Function; } -interface IJSenSettings { +interface IJsenSettings { missing$Ref?: boolean; greedy?: boolean; formats?: IJsenFormats; schemas?: any; } -interface IJsenBuildSettings extends IJSenSettings { +interface IJsenBuildSettings { copy?: boolean; additionalProperties?: boolean; } @@ -36,7 +36,7 @@ interface IJsenUnique { findIndex(array: any[], value: any, comparator: (obj1: any, obj2: any) => boolean): number; } interface IJsen { - (schema?: any, options?: IJSenSettings): IJsenValidator; + (schema?: any, options?: IJsenSettings): IJsenValidator; clone(data: any): any; equal(a: any, b: any): boolean; unique: IJsenUnique; From 596756140de06049a4228b0206d96c0c5b2a401c Mon Sep 17 00:00:00 2001 From: marinewater Date: Sun, 27 Mar 2016 01:46:28 +0100 Subject: [PATCH 12/53] Update fromnow-tests.ts --- fromnow/fromnow-tests.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/fromnow/fromnow-tests.ts b/fromnow/fromnow-tests.ts index b95a23640..4ed78816a 100644 --- a/fromnow/fromnow-tests.ts +++ b/fromnow/fromnow-tests.ts @@ -6,6 +6,10 @@ function dateOnly() { fromnow( '2015-12-31' ); } +function dateObjectOnly() { + fromnow( new Date() ); +} + function maxChunks() { fromnow( '2015-12-31', { maxChunks: 12 @@ -22,4 +26,4 @@ function useAnd() { fromnow( '2015-12-31', { useAnd: true }); -} \ No newline at end of file +} From c2da4112f2f4b075d05cdc057200ff2b6255b986 Mon Sep 17 00:00:00 2001 From: marinewater Date: Sun, 27 Mar 2016 01:48:20 +0100 Subject: [PATCH 13/53] Update fromnow.d.ts --- fromnow/fromnow.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fromnow/fromnow.d.ts b/fromnow/fromnow.d.ts index ea7ef657a..d2b90891e 100644 --- a/fromnow/fromnow.d.ts +++ b/fromnow/fromnow.d.ts @@ -12,13 +12,13 @@ declare namespace FromNow { export interface FromNowStatic { /** * Get readable time differences from now vs past or future dates. - * @param {string} date + * @param {string|Date} date * @param {object} [opts] * @param {number} [opts.maxChucks=10] * @param {boolean} [opts.useAgo=false] * @param {boolean} [opts.useAnd=false] */ - (date: string, opts?: FromNowOpts): string + (date: string|Date, opts?: FromNowOpts): string } } From c67a3b8d61e023fc49732c44a97c1d731e45d16a Mon Sep 17 00:00:00 2001 From: Leo Liang Date: Sun, 27 Mar 2016 16:33:22 +0800 Subject: [PATCH 14/53] oracledb.d.ts : access object property in result rows --- oracledb/oracledb-tests.ts | 1 + oracledb/oracledb.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/oracledb/oracledb-tests.ts b/oracledb/oracledb-tests.ts index 2fca17bc9..35206fe57 100644 --- a/oracledb/oracledb-tests.ts +++ b/oracledb/oracledb-tests.ts @@ -23,6 +23,7 @@ OracleDB.getConnection( console.error(err.message); return; } console.log(result.rows); + console.log(result.rows[0].department_id); // when outFormet is OBJECT } ); } diff --git a/oracledb/oracledb.d.ts b/oracledb/oracledb.d.ts index 3c803139f..6c05efeaa 100644 --- a/oracledb/oracledb.d.ts +++ b/oracledb/oracledb.d.ts @@ -93,7 +93,7 @@ declare module 'oracledb' { /** Metadata information - just columns names for now. */ metaData?: Array; /** When not using ResultSet, query results comes here. */ - rows?: Array> | Array; + rows?: Array> | Array; /** When using ResultSet, query results comes here. */ resultSet?: IResultSet; } From f05cda287f2daec33125112655e59ef3fe93a958 Mon Sep 17 00:00:00 2001 From: Crevil Date: Sun, 27 Mar 2016 14:00:36 +0200 Subject: [PATCH 15/53] Add ng-facebook typings --- ng-facebook/ng-facebook-tests.ts | 51 ++++++++++++++++++++++++++++++++ ng-facebook/ng-facebook.d.ts | 46 ++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 ng-facebook/ng-facebook-tests.ts create mode 100644 ng-facebook/ng-facebook.d.ts diff --git a/ng-facebook/ng-facebook-tests.ts b/ng-facebook/ng-facebook-tests.ts new file mode 100644 index 000000000..9aace5d14 --- /dev/null +++ b/ng-facebook/ng-facebook-tests.ts @@ -0,0 +1,51 @@ +/// + +{ + let $facebookProvider: angular.ngFacebook.IFacebookProvider; + + $facebookProvider + .setAppId("764262530321266") + .setPermissions(["email", "user_friends"]) + .setPermissions("user_friends") + .setCustomInit({ + xfbml: true + }) + .setVersion("v2.2"); + + let appId: string = $facebookProvider.getAppId(); + let version: string = $facebookProvider.getVersion(); + let permissions: string = $facebookProvider.getPermissions(); + let customInit: any = $facebookProvider.getCustomInit(); +} + +{ + let $facebook: angular.ngFacebook.IFacebookService; + + let customInit: FBInitParams = $facebook.config("customInit"); + let version: string = $facebook.config("version"); + let appId: string = $facebook.config("appId"); + + $facebook.init(); + + $facebook.setCache("key1", 123); + $facebook.setCache<{ prop1: number }>("key2", { prop1: 456 }); + let cache: number = $facebook.getCache("key"); + $facebook.clearCache(); + + let isConnected: boolean = $facebook.isConnected(); + + let authResponse: {} = $facebook.getAuthResponse(); + + $facebook.getLoginStatus().then(status => { }); + $facebook.getLoginStatus(true).then(status => { }); + + $facebook.logout().then(() => { }); + $facebook.login().then(() => { }); + + $facebook.api("/me").then(user => { }); + $facebook.api("/me", "get"); + $facebook.api("/me", { param: 1 }); + $facebook.api("/me", "get", { param: 1 }); + + $facebook.cachedApi("'/me/friends").then(friends => { }); +} diff --git a/ng-facebook/ng-facebook.d.ts b/ng-facebook/ng-facebook.d.ts new file mode 100644 index 000000000..dc2adc883 --- /dev/null +++ b/ng-facebook/ng-facebook.d.ts @@ -0,0 +1,46 @@ +// Type definitions for ng-facebook +// Project: https://github.com/GoDisco/ngFacebook +// Definitions by: Crevil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare namespace angular.ngFacebook { + interface IFacebookProvider { + setAppId(appId: string): IFacebookProvider; + getAppId(): string; + + setVersion(version: string): IFacebookProvider; + getVersion(): string; + + setPermissions(permissions: string|Array): IFacebookProvider; + getPermissions(): string; + + setCustomInit(customInit: FBInitParams): IFacebookProvider; + getCustomInit(): FBInitParams; + } + + interface IFacebookService { + config(property: string): T; + init(): void; + + setCache(attr: string, val: T): void; + getCache(attr: string): T; + clearCache(): void; + + isConnected(): boolean; + getAuthResponse(): {}; + getLoginStatus(force?: boolean): angular.IPromise<{}>; + login(permissions?: string, rerequest?: boolean): angular.IPromise<{}>; + logout(): angular.IPromise; + + ui(params: FBUIParams): angular.IPromise; + api(path: string): angular.IPromise<{}>; + api(path: string, method: string): angular.IPromise<{}>; + api(path: string, params: Object): angular.IPromise<{}>; + api(path: string, method: string, params: Object): angular.IPromise<{}>; + + cachedApi(path: string): angular.IPromise; + } +} From 5653cd33a755cfe47ebf36968b0f00e1d36364cc Mon Sep 17 00:00:00 2001 From: Crevil Date: Sun, 27 Mar 2016 14:06:08 +0200 Subject: [PATCH 16/53] Update protractor-http-mock to v0.4.0 --- .../protractor-http-mock-tests.ts | 366 ++++++++++-------- .../protractor-http-mock.d.ts | 43 +- 2 files changed, 231 insertions(+), 178 deletions(-) diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts index 6c39f1401..e6620d015 100644 --- a/protractor-http-mock/protractor-http-mock-tests.ts +++ b/protractor-http-mock/protractor-http-mock-tests.ts @@ -1,212 +1,242 @@ /// -function TestConfig() { +function TestConfig() { mock.config = { - rootDirectory: 'root', - protractorConfig: 'protractor.conf.js' - }; + rootDirectory: "root", + protractorConfig: "protractor.conf.js" + }; } function TestCtorOverloads() { - let noParam: mock.ProtractorHttpMock = mock(); + let noParam: mock.ProtractorHttpMock = mock(); let emptyArray: mock.ProtractorHttpMock = mock([]); - let mockFiles: mock.ProtractorHttpMock = mock(['mock1', 'mock2']); - let skipDefaults: mock.ProtractorHttpMock = mock([], true); + let mockFiles: mock.ProtractorHttpMock = mock(["mock1", "mock2"]); + let skipDefaults: mock.ProtractorHttpMock = mock([], true); - let del: mock.requests.Delete = { - request: { - path: 'path', - method: 'DELETE' - }, - response: { - status: 400, - data: 1 - } - }; - let put: mock.requests.Put = { - request: { - path: 'path', - method: 'PUT' - }, - response: { - status: 400, - data: 1 - } - }; - let mocks: mock.ProtractorHttpMock = mock([del, put]); + let del: mock.requests.Delete = { + request: { + path: "path", + method: "DELETE" + }, + response: { + status: 400, + data: 1 + } + }; + let put: mock.requests.Put = { + request: { + path: "path", + method: "PUT" + }, + response: { + status: 400, + data: 1 + } + }; + let mocks: mock.ProtractorHttpMock = mock([del, put]); } function TestTeardown() { - mock.teardown(); + mock.teardown(); } function TestRequestsMade() { - let values: Array; - mock.requestsMade().then(v => values = v); + let values: Array; + mock.requestsMade().then(v => values = v); } function TestClearRequests() { - let promiseValue: boolean; - mock.clearRequests().then(value => { - promiseValue = value; - }); + let promiseValue: boolean; + mock.clearRequests().then(value => { + promiseValue = value; + }); +} + +function TestDynamicAdd() { + let put: mock.requests.Put = { + request: { + path: "path", + method: "PUT" + }, + response: { + status: 400, + data: 1 + } + }; + let resolved: boolean; + mock.add([put]).then(r => resolved = r); +} + +function TestDyanmicRemove() { + let put: mock.requests.Put = { + request: { + path: "path", + method: "PUT" + }, + response: { + status: 400, + data: 1 + } + }; + let resolved: boolean; + mock.remove([put]).then(r => resolved = r); } function TestGetRequestDefinitions() { - let getMinium: mock.requests.Get = { - request: { - path: 'path', - method: 'GET' - }, - response: { - data: 1, - status: 500 - } - }; + let getMinium: mock.requests.Get = { + request: { + path: "path", + method: "GET" + }, + response: { + data: 1, + status: 500 + } + }; - let getParams: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - params: { - param1: 'param1', - param2: 2 - } - }, - response: { - data: 1, - status: 500 - } - }; + let getParams: mock.requests.Get = { + request: { + path: "path", + method: "GET", + params: { + param1: "param1", + param2: 2 + } + }, + response: { + data: 1, + status: 500 + } + }; - let post: mock.requests.Post = { - request: { - path: 'path', - method: 'POST' - }, - response: { - data: 1, - status: 500 - } - }; + let post: mock.requests.Post = { + request: { + path: "path", + method: "POST" + }, + response: { + data: 1, + status: 500 + } + }; - let getQueryString: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - queryString: { - query1: 'query1', - query2: 2 - } - }, - response: { - data: 1, - status: 500 - } - }; + let getQueryString: mock.requests.Get = { + request: { + path: "path", + method: "GET", + queryString: { + query1: "query1", + query2: 2 + } + }, + response: { + data: 1, + status: 500 + } + }; - let getHeaders: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - headers: { - head1: 'head1', - head2: 'head2' - } - }, - response: { - data: 1, - status: 500 - } - }; + let getHeaders: mock.requests.Get = { + request: { + path: "path", + method: "GET", + headers: { + head1: "head1", + head2: "head2" + } + }, + response: { + data: 1, + status: 500 + } + }; } function TestPostRequestDefinitions() { - let post: mock.requests.Post = { - request: { - path: 'path', - method: 'POST' - }, - response: { - data: 1, - status: 500 - } - }; + let post: mock.requests.Post = { + request: { + path: "path", + method: "POST" + }, + response: { + data: 1, + status: 500 + } + }; - let postData: mock.requests.PostData = { - request: { - path: 'path', - method: 'POST', - data: 'data' - }, - response: { - data: 1, - status: 500 - } - }; + let postData: mock.requests.PostData = { + request: { + path: "path", + method: "POST", + data: "data" + }, + response: { + data: 1, + status: 500 + } + }; } function TestHeadRequestDefinitions() { - let head: mock.requests.Head = { - request: { - path: 'path', - method: 'HEAD' - }, - response: { - status: 500, - data: 1 - } - }; + let head: mock.requests.Head = { + request: { + path: "path", + method: "HEAD" + }, + response: { + status: 500, + data: 1 + } + }; } function TestDeleteRequestDefinitions() { - let del: mock.requests.Delete = { - request: { - path: 'path', - method: 'DELETE' - }, - response: { - status: 500, - data: 1 - } - }; + let del: mock.requests.Delete = { + request: { + path: "path", + method: "DELETE" + }, + response: { + status: 500, + data: 1 + } + }; } function TestPutRequestDefinitions() { - let put: mock.requests.Put = { - request: { - path: 'path', - method: 'PUT' - }, - response: { - status: 500, - data: 1 - } - }; + let put: mock.requests.Put = { + request: { + path: "path", + method: "PUT" + }, + response: { + status: 500, + data: 1 + } + }; } function TestPatchRequestDefinitions() { - let patch: mock.requests.Patch = { - request: { - path: 'path', - method: 'PATCH' - }, - response: { - status: 500, - data: 1 - } - }; + let patch: mock.requests.Patch = { + request: { + path: "path", + method: "PATCH" + }, + response: { + status: 500, + data: 1 + } + }; } function TestJsonpRequestDefinitions() { - let jsonp: mock.requests.Jsonp = { - request: { - path: 'path', - method: 'JSONP' - }, - response: { - status: 500, - data: 1 - } - }; + let jsonp: mock.requests.Jsonp = { + request: { + path: "path", + method: "JSONP" + }, + response: { + status: 500, + data: 1 + } + }; } diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index dcb2345d2..b953d8eb2 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -57,6 +57,24 @@ declare namespace mock { */ protractorConfig?: string; }; + + /** + * Add mock dynamically. + * Returns a promise that will be resolved with a true boolean + * when mocks have been added. + * + * @param mocks An array of mock modules to load into the application. + */ + add(mocks: Array>): webdriver.promise.Promise; + + /** + * Remove mock dynamically. + * Returns a promise that will be resolved with a true boolean + * when mocks have been removed. + * + * @param mocks An array of mock modules to remove from the application. + */ + remove(mocks: Array>): webdriver.promise.Promise; } /** @@ -68,12 +86,17 @@ declare namespace mock { } namespace requests { + /** + * Request methods type + */ + type Method = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "PATCH" | "JSONP"; + /** * Base request mock used for all mocks. */ interface BaseRequest { request: { - method: string; + method: Method; path: string; }; response: { @@ -87,7 +110,7 @@ declare namespace mock { */ interface Get extends BaseRequest { request: { - method: string; + method: Method; path: string; params?: Object; queryString?: Object; @@ -107,7 +130,7 @@ declare namespace mock { interface PostData extends BaseRequest { request: { path: string; - method: string; + method: Method; data: TPayload; }; response: { @@ -122,7 +145,7 @@ declare namespace mock { interface Post extends BaseRequest { request: { path: string; - method: string; + method: Method; }; response: { status: number; @@ -136,7 +159,7 @@ declare namespace mock { interface Head extends BaseRequest { request: { path: string; - method: string; + method: Method; }; response: { status: number; @@ -150,7 +173,7 @@ declare namespace mock { interface Delete extends BaseRequest { request: { path: string; - method: string; + method: Method; }; response: { status: number; @@ -164,7 +187,7 @@ declare namespace mock { interface Put extends BaseRequest { request: { path: string; - method: string; + method: Method; }; response: { status: number; @@ -178,7 +201,7 @@ declare namespace mock { interface Patch extends BaseRequest { request: { path: string; - method: string; + method: Method; }; response: { status: number; @@ -192,7 +215,7 @@ declare namespace mock { interface Jsonp extends BaseRequest { request: { path: string; - method: string; + method: Method; }; response: { status: number; @@ -204,6 +227,6 @@ declare namespace mock { declare var mock: mock.ProtractorHttpMock; -declare module 'protractor-http-mock' { +declare module "protractor-http-mock" { export = mock; } From 822864b08cee6821527183b097ba996c715641b5 Mon Sep 17 00:00:00 2001 From: Jussi Kinnula Date: Sun, 27 Mar 2016 16:16:27 +0300 Subject: [PATCH 17/53] dotenv: Use correct GitHub link --- dotenv/dotenv.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotenv/dotenv.d.ts b/dotenv/dotenv.d.ts index f0633e88f..b18e9bd03 100644 --- a/dotenv/dotenv.d.ts +++ b/dotenv/dotenv.d.ts @@ -1,5 +1,5 @@ // Type definitions for dotenv 2.0.0 -// Project: https://github.com/bkeepers/dotenv +// Project: https://github.com/motdotla/dotenv // Definitions by: Jussi Kinnula // Definitions: https://github.com/jussikinnula/DefinitelyTyped From 06f39135fe0eace3eda5dd01d3af9b8f79938197 Mon Sep 17 00:00:00 2001 From: Andrew Kuklewicz Date: Sun, 27 Mar 2016 18:46:49 -0400 Subject: [PATCH 18/53] Add type definition and tests for EvaporateJS --- evaporate/evaporate-tests.ts | 7 +++++++ evaporate/evaporate.d.ts | 13 +++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 evaporate/evaporate-tests.ts create mode 100644 evaporate/evaporate.d.ts diff --git a/evaporate/evaporate-tests.ts b/evaporate/evaporate-tests.ts new file mode 100644 index 000000000..559d61fe7 --- /dev/null +++ b/evaporate/evaporate-tests.ts @@ -0,0 +1,7 @@ +/// + +function test_upload() { + var evaporate = new Evaporate({}); + var uploadId = evaporate.add({}); + evaporate.cancel(uploadId); +} diff --git a/evaporate/evaporate.d.ts b/evaporate/evaporate.d.ts new file mode 100644 index 000000000..07c82325f --- /dev/null +++ b/evaporate/evaporate.d.ts @@ -0,0 +1,13 @@ +// Type definitions for EvaporateJS +// Project: https://github.com/TTLabs/EvaporateJS +// Definitions by: Andrew Kuklewicz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare class Evaporate { + cancel(id:string): boolean; + constructor(config:any); + add(config:any): string; +} + +declare module 'evaporate' { + export = Evaporate; +} From cbf802150d720a8259a350d4f0a8b198813c0202 Mon Sep 17 00:00:00 2001 From: Andrew Kuklewicz Date: Sun, 27 Mar 2016 19:28:44 -0400 Subject: [PATCH 19/53] Add (much deserved credit) for Rhoden --- evaporate/evaporate.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/evaporate/evaporate.d.ts b/evaporate/evaporate.d.ts index 07c82325f..2a6745546 100644 --- a/evaporate/evaporate.d.ts +++ b/evaporate/evaporate.d.ts @@ -1,6 +1,6 @@ // Type definitions for EvaporateJS // Project: https://github.com/TTLabs/EvaporateJS -// Definitions by: Andrew Kuklewicz +// Definitions by: Andrew Kuklewicz , Chris Rhoden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare class Evaporate { cancel(id:string): boolean; From f0f6c7f00d2dbc635030dfdc3fb3c8c4fc565362 Mon Sep 17 00:00:00 2001 From: bmiller1 Date: Sun, 27 Mar 2016 21:52:52 -0500 Subject: [PATCH 20/53] Added remove() function to MapsEventListener See https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapsEventListener --- googlemaps/google.maps.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 14075c446..65776131d 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1638,7 +1638,10 @@ declare namespace google.maps { } /***** Events *****/ - export interface MapsEventListener { } + export interface MapsEventListener { + /** Removes the listener. Equivalent to calling google.maps.event.removeListener(listener). */ + remove(): void; + } export class event { /** From 234ca8dab0a5f123d12de0201c6895a7740bfeea Mon Sep 17 00:00:00 2001 From: Kohei Hisakuni Date: Sun, 27 Mar 2016 20:44:17 -0700 Subject: [PATCH 21/53] Add overloaded method. --- gapi/gapi.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/gapi/gapi.d.ts b/gapi/gapi.d.ts index 9a5f32eba..d1481d28c 100644 --- a/gapi/gapi.d.ts +++ b/gapi/gapi.d.ts @@ -127,6 +127,14 @@ declare namespace gapi.auth { } declare namespace gapi.client { + /** + * Loads the client library interface to a particular API. If a callback is not provided, a promise is returned. + * @param name The name of the API to load. + * @param version The version of the API to load. + * @return promise The promise that get's resolved after the request is finished. + */ + export function load(name: string, version: string): Promise + /** * Loads the client library interface to a particular API. The new API interface will be in the form gapi.client.api.collection.method. * @param name The name of the API to load. From d4d4286f7a33e78a68fd4f78b2ae70e07e500fe7 Mon Sep 17 00:00:00 2001 From: SquadWuschel Date: Mon, 28 Mar 2016 11:45:19 +0200 Subject: [PATCH 22/53] Changed Promise to IPromise The current TypeDefinition with Promise was not working any more, can't find the Promise its needed to be renamed to IPromise. --- angularjs/angular-component-router.d.ts | 38 ++++++++++++------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/angularjs/angular-component-router.d.ts b/angularjs/angular-component-router.d.ts index e015a712a..2c56ef3a2 100644 --- a/angularjs/angular-component-router.d.ts +++ b/angularjs/angular-component-router.d.ts @@ -45,7 +45,7 @@ declare namespace angular { specificity(): number; - resolveComponent(): Promise; + resolveComponent(): IPromise; /** * converts the instruction into a URL string @@ -87,20 +87,20 @@ declare namespace angular { * Called by the Router to instantiate a new component during the commit phase of a navigation. * This method in turn is responsible for calling the `routerOnActivate` hook of its child. */ - activate(nextInstruction: ComponentInstruction): Promise; + activate(nextInstruction: ComponentInstruction): IPromise; /** * Called by the {@link Router} during the commit phase of a navigation when an outlet * reuses a component between different routes. * This method in turn is responsible for calling the `routerOnReuse` hook of its child. */ - reuse(nextInstruction: ComponentInstruction): Promise; + reuse(nextInstruction: ComponentInstruction): IPromise; /** * Called by the {@link Router} when an outlet disposes of a component's contents. * This method in turn is responsible for calling the `routerOnDeactivate` hook of its child. */ - deactivate(nextInstruction: ComponentInstruction): Promise; + deactivate(nextInstruction: ComponentInstruction): IPromise; /** * Called by the {@link Router} during recognition phase of a navigation. @@ -110,7 +110,7 @@ declare namespace angular { * This method delegates to the child component's `routerCanDeactivate` hook if it exists, * and otherwise resolves to true. */ - routerCanDeactivate(nextInstruction: ComponentInstruction): Promise; + routerCanDeactivate(nextInstruction: ComponentInstruction): IPromise; /** * Called by the {@link Router} during recognition phase of a navigation. @@ -122,7 +122,7 @@ declare namespace angular { * Otherwise, this method delegates to the child component's `routerCanReuse` hook if it exists, * or resolves to true if the hook is not present. */ - routerCanReuse(nextInstruction: ComponentInstruction): Promise; + routerCanReuse(nextInstruction: ComponentInstruction): IPromise; } interface RouteRegistry { @@ -140,7 +140,7 @@ declare namespace angular { * Given a URL and a parent component, return the most specific instruction for navigating * the application into the state specified by the url */ - recognize(url: string, ancestorInstructions: Instruction[]): Promise; + recognize(url: string, ancestorInstructions: Instruction[]): IPromise; /** * Given a normalized list with component names and params like: `['user', {id: 3 }]` @@ -197,14 +197,14 @@ declare namespace angular { * * You probably don't need to use this unless you're writing a reusable component. */ - registerPrimaryOutlet(outlet: RouterOutlet): Promise; + registerPrimaryOutlet(outlet: RouterOutlet): IPromise; /** * Register an outlet to notified of auxiliary route changes. * * You probably don't need to use this unless you're writing a reusable component. */ - registerAuxOutlet(outlet: RouterOutlet): Promise; + registerAuxOutlet(outlet: RouterOutlet): IPromise; /** * Given an instruction, returns `true` if the instruction is currently active, @@ -224,7 +224,7 @@ declare namespace angular { * ]); * ``` */ - config(definitions: RouteDefinition[]): Promise; + config(definitions: RouteDefinition[]): IPromise; /** * Navigate based on the provided Route Link DSL. It's preferred to navigate with this method @@ -238,7 +238,7 @@ declare namespace angular { * ``` * See the {@link RouterLink} directive for more. */ - navigate(linkParams: any[]): Promise; + navigate(linkParams: any[]): IPromise; /** * Navigate to a URL. Returns a promise that resolves when navigation is complete. @@ -247,19 +247,19 @@ declare namespace angular { * If the given URL begins with a `/`, router will navigate absolutely. * If the given URL does not begin with `/`, the router will navigate relative to this component. */ - navigateByUrl(url: string, _skipLocationChange?: boolean): Promise; + navigateByUrl(url: string, _skipLocationChange?: boolean): IPromise; /** * Navigate via the provided instruction. Returns a promise that resolves when navigation is * complete. */ navigateByInstruction(instruction: Instruction, - _skipLocationChange?: boolean): Promise; + _skipLocationChange?: boolean): IPromise; /** * Updates this router and all descendant routers according to the given instruction */ - commit(instruction: Instruction, _skipLocationChange?: boolean): Promise; + commit(instruction: Instruction, _skipLocationChange?: boolean): IPromise; /** * Subscribe to URL updates from the router @@ -269,18 +269,18 @@ declare namespace angular { /** * Removes the contents of this router's outlet and all descendant outlets */ - deactivate(instruction: Instruction): Promise; + deactivate(instruction: Instruction): IPromise; /** * Given a URL, returns an instruction representing the component graph */ - recognize(url: string): Promise; + recognize(url: string): IPromise; /** * Navigates to either the last URL successfully navigated to, or the last URL requested if the * router has yet to successfully navigate. */ - renavigate(): Promise; + renavigate(): IPromise; /** * Generate an `Instruction` based on the provided Route Link DSL. @@ -364,7 +364,7 @@ declare namespace angular { * {@example router/ts/can_deactivate/can_deactivate_example.ts region='routerCanDeactivate'} */ interface CanDeactivate { - $routerCanDeactivate(next?: ComponentInstruction, prev?: ComponentInstruction): boolean | Promise; + $routerCanDeactivate(next?: ComponentInstruction, prev?: ComponentInstruction): boolean | IPromise; } /** @@ -407,7 +407,7 @@ declare namespace angular { * {@example router/ts/reuse/reuse_example.ts region='reuseCmp'} */ interface CanReuse { - $routerCanReuse(next?: angular.ComponentInstruction, prev?: angular.ComponentInstruction): boolean | Promise; + $routerCanReuse(next?: angular.ComponentInstruction, prev?: angular.ComponentInstruction): boolean | IPromise; } /** From 0aa772c53fa6bf700f5ddce007871260297001f3 Mon Sep 17 00:00:00 2001 From: Brendon Colburn Date: Mon, 28 Mar 2016 08:58:10 -0400 Subject: [PATCH 23/53] Overload for custom scope interfaces I recently came up with this solution so I could leverage my custom scope when grabbing the scope from a controller using angular.element. It works well and with the it ensures that you can only set it to an interface that extends IScope. --- angularjs/angular.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 6d72c4e2d..e86fd3705 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1845,6 +1845,11 @@ declare namespace angular { controller(name: string): any; injector(): any; scope(): IScope; + + /** + * Overload for custom scope interfaces + */ + scope(): T; isolateScope(): IScope; inheritedData(key: string, value: any): JQuery; From 967db8dd4cfe66faa06f08a4ad6a396ccbf081ec Mon Sep 17 00:00:00 2001 From: Konstantin Burkalev Date: Mon, 28 Mar 2016 16:55:11 +0300 Subject: [PATCH 24/53] Added definitions for Wampy object --- wampy/wampy-tests.d.ts | 0 wampy/wampy.d.ts | 87 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 wampy/wampy-tests.d.ts create mode 100644 wampy/wampy.d.ts diff --git a/wampy/wampy-tests.d.ts b/wampy/wampy-tests.d.ts new file mode 100644 index 000000000..e69de29bb diff --git a/wampy/wampy.d.ts b/wampy/wampy.d.ts new file mode 100644 index 000000000..245c2f834 --- /dev/null +++ b/wampy/wampy.d.ts @@ -0,0 +1,87 @@ +// Type definitions for wampy.js v2.0.1 +// Project: https://github.com/KSDaemon/wampy.js +// Definitions by: Konstantin Burkalev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface WampyOptions { + autoReconnect?: boolean; + reconnectInterval?: number; + maxRetries?: number; + transportEncoding?: string; + realm?: string; + helloCustomDetails?: any; + onConnect?: () => void; + onClose?: () => void; + onError?: () => void; + onReconnect?: () => void; + ws?: any; + msgpackCoder?: any; +} + +interface WampyOpStatus { + code: number; + description: string; + reqId?: number; +} + +interface SuccessErrorCallbacksHash { + onSuccess?: () => void; + onError?: (err: string) => void; +} + +interface SubscribeCallbacksHash extends SuccessErrorCallbacksHash { + onEvent: (data: any) => void; +} + +interface RegisterCallbacksHash extends SuccessErrorCallbacksHash { + rpc: (data: any) => any; +} + +interface AdvancedOptions { + exclude?: number | number[]; + eligible?: number | number[]; + exclude_me?: boolean; + disclose_me?: boolean; +} + +interface CallAdvancedOptions extends AdvancedOptions { + receive_progress?: boolean; +} + +interface CancelAdvancedOptions { + mode?: "skip" | "kill" | "killnowait"; +} + +interface Wampy { + options(opts?: WampyOptions): WampyOptions | Wampy; + getOpStatus(): WampyOpStatus; + getSessionId(): number; + connect(url?: string): Wampy; + disconnect(): Wampy; + abort(): Wampy; + subscribe(topicURI: string, callbacks: (() => void | SubscribeCallbacksHash)): Wampy; + unsubscribe(topicURI: string, callbacks: (() => void | SubscribeCallbacksHash)): Wampy; + publish(topicURI: string, + payload?: any, + callbacks?: SuccessErrorCallbacksHash, + advancedOptions?: AdvancedOptions): Wampy; + call(topicURI: string, + payload?: any, + callbacks?: (() => void | SuccessErrorCallbacksHash), + advancedOptions?: CallAdvancedOptions): Wampy; + cancel(reqId: number, + callbacks?: (() => void | SuccessErrorCallbacksHash), + advancedOptions?: CancelAdvancedOptions): Wampy; + register(topicURI: string, callbacks: ((data: any) => any | RegisterCallbacksHash)): Wampy; + unregister(topicURI: string, callbacks?: (() => void | SuccessErrorCallbacksHash)): Wampy; +} + +interface WampyInstance { + new(url?: string, options?: WampyOptions): Wampy; +} + +declare var wampy: WampyInstance; + +declare module "wampy" { + export = wampy; +} From e821f19879433fe5d9f7e9e5b8d92758591f66cf Mon Sep 17 00:00:00 2001 From: Timothy Soehnlin Date: Mon, 28 Mar 2016 09:25:50 -0500 Subject: [PATCH 25/53] Update gm.d.ts Supporting alternate constructors listed at https://github.com/aheckmann/gm#constructor --- gm/gm.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/gm/gm.d.ts b/gm/gm.d.ts index d7272397e..9f7d027f1 100644 --- a/gm/gm.d.ts +++ b/gm/gm.d.ts @@ -9,6 +9,9 @@ declare module "gm" { import stream = require('stream'); function m(image: string): m.State; + function m(stream:NodeJS.ReadableStream, image?: string): m.State; + function m(stream:Buffer, image?: string): m.State; + function m(width:number, height:number, color?:string): m.State; namespace m { export interface ClassOptions { From 6d218806c8c8e8785d497eb91616ca4140b23f74 Mon Sep 17 00:00:00 2001 From: Timothy Soehnlin Date: Mon, 28 Mar 2016 09:28:02 -0500 Subject: [PATCH 26/53] Update gm.d.ts Renaming stream to buffer for consistency --- gm/gm.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gm/gm.d.ts b/gm/gm.d.ts index 9f7d027f1..964decdee 100644 --- a/gm/gm.d.ts +++ b/gm/gm.d.ts @@ -10,7 +10,7 @@ declare module "gm" { function m(image: string): m.State; function m(stream:NodeJS.ReadableStream, image?: string): m.State; - function m(stream:Buffer, image?: string): m.State; + function m(buffer:Buffer, image?: string): m.State; function m(width:number, height:number, color?:string): m.State; namespace m { From c5344fa9139b10ec4809a1fabc5cab0b249c0a56 Mon Sep 17 00:00:00 2001 From: Konstantin Burkalev Date: Mon, 28 Mar 2016 17:58:22 +0300 Subject: [PATCH 27/53] Fixed and added tests --- wampy/wampy-tests.d.ts | 0 wampy/wampy-tests.ts | 119 ++++++++++++++++++++++++++++++ wampy/wampy.d.ts | 164 +++++++++++++++++++++-------------------- 3 files changed, 204 insertions(+), 79 deletions(-) delete mode 100644 wampy/wampy-tests.d.ts create mode 100644 wampy/wampy-tests.ts diff --git a/wampy/wampy-tests.d.ts b/wampy/wampy-tests.d.ts deleted file mode 100644 index e69de29bb..000000000 diff --git a/wampy/wampy-tests.ts b/wampy/wampy-tests.ts new file mode 100644 index 000000000..eeea0132d --- /dev/null +++ b/wampy/wampy-tests.ts @@ -0,0 +1,119 @@ +/// +/// + +import Wampy = require('wampy'); + +var ws = new Wampy('http://wamp.router.url', {realm: 'WAMPRealm'}); + +ws.options(); + +ws.options({ + reconnectInterval: 1000, + maxRetries: 999, + onConnect: function () { console.log('Yahoo! We are online!'); }, + onClose: function () { console.log('See you next time!'); }, + onError: function () { console.log('Breakdown happened'); }, + onReconnect: function () { console.log('Reconnecting...'); } +}); + +ws.connect(); +ws.connect('/my-socket-path'); +ws.connect('wss://socket.server.com:5000/ws'); +var id: number = ws.getSessionId(); +ws.disconnect(); +ws.abort(); + +ws.subscribe('system.monitor.update', function (data) { + console.log('Received system.monitor.update event!'); + }) + .subscribe('client.message', function (data) { + console.log('Received client.message event!'); + }); + +var f1 = function () { console.log('Subscribe processing!'); }; +ws.unsubscribe('subscribed.topic', f1); + +ws.unsubscribe('chat.message.received'); + +ws.call('get.server.time', null, { + onSuccess: function (stime) { + console.log('RPC successfully called'); + console.log('Server time is ' + stime); + }, + onError: function (err) { + console.log('RPC call failed with error ' + err); + } +}); + +ws.publish('system.monitor.update'); +ws.getOpStatus(); + +ws.publish('user.logged.in'); +ws.publish('chat.message.received', 'user message'); +ws.publish('chat.message.received', ['user message1', 'user message2']); +ws.publish('user.modified', { field1: 'field1', field2: true, field3: 123 }); +ws.publish('user.modified', { field1: 'field1', field2: true, field3: 123 }, { + onSuccess: function () { console.log('User successfully modified'); } +}); +ws.publish('user.modified', { field1: 'field1', field2: true, field3: 123 }, { + onSuccess: function () { console.log('User successfully modified'); }, + onError: function (err) { console.log('User modification failed', err); } +}); +ws.publish('chat.message.received', ['Private message'], null, { eligible: 123456789 }); + +ws.call('server.time', null, function (data) { console.log('Server time is ' + data[0]); }); + +ws.call('start.migration', null, { + onSuccess: function (data) { + console.log('RPC successfully called'); + }, + onError: function (err) { + console.log('RPC call failed!',err); + } +}); + +ws.call('restore.backup', { backupFile: 'backup.zip' }, { + onSuccess: function (data) { + console.log('Backup successfully restored'); + }, + onError: function (err) { + console.log('Restore failed!',err); + } +}); + +ws.call('start.migration', null, { + onSuccess: function (data) { + console.log('RPC successfully called'); + }, + onError: function (err) { + console.log('RPC call failed!',err); + } +}); +var status = ws.getOpStatus(); + +ws.cancel(status.reqId); + +var sqrt_f = function (x: number) { return x*x; }; + +ws.register('sqrt.value', sqrt_f); + +ws.register('sqrt.value', { + rpc: sqrt_f, + onSuccess: function (data) { + console.log('RPC successfully registered'); + }, + onError: function (err) { + console.log('RPC registration failed!',err); + } +}); + +ws.unregister('sqrt.value'); + +ws.unregister('sqrt.value', { + onSuccess: function (data) { + console.log('RPC successfully unregistered'); + }, + onError: function (err) { + console.log('RPC unregistration failed!',err); + } +}); diff --git a/wampy/wampy.d.ts b/wampy/wampy.d.ts index 245c2f834..4c94eb0dd 100644 --- a/wampy/wampy.d.ts +++ b/wampy/wampy.d.ts @@ -3,85 +3,91 @@ // Definitions by: Konstantin Burkalev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface WampyOptions { - autoReconnect?: boolean; - reconnectInterval?: number; - maxRetries?: number; - transportEncoding?: string; - realm?: string; - helloCustomDetails?: any; - onConnect?: () => void; - onClose?: () => void; - onError?: () => void; - onReconnect?: () => void; - ws?: any; - msgpackCoder?: any; -} - -interface WampyOpStatus { - code: number; - description: string; - reqId?: number; -} - -interface SuccessErrorCallbacksHash { - onSuccess?: () => void; - onError?: (err: string) => void; -} - -interface SubscribeCallbacksHash extends SuccessErrorCallbacksHash { - onEvent: (data: any) => void; -} - -interface RegisterCallbacksHash extends SuccessErrorCallbacksHash { - rpc: (data: any) => any; -} - -interface AdvancedOptions { - exclude?: number | number[]; - eligible?: number | number[]; - exclude_me?: boolean; - disclose_me?: boolean; -} - -interface CallAdvancedOptions extends AdvancedOptions { - receive_progress?: boolean; -} - -interface CancelAdvancedOptions { - mode?: "skip" | "kill" | "killnowait"; -} - -interface Wampy { - options(opts?: WampyOptions): WampyOptions | Wampy; - getOpStatus(): WampyOpStatus; - getSessionId(): number; - connect(url?: string): Wampy; - disconnect(): Wampy; - abort(): Wampy; - subscribe(topicURI: string, callbacks: (() => void | SubscribeCallbacksHash)): Wampy; - unsubscribe(topicURI: string, callbacks: (() => void | SubscribeCallbacksHash)): Wampy; - publish(topicURI: string, - payload?: any, - callbacks?: SuccessErrorCallbacksHash, - advancedOptions?: AdvancedOptions): Wampy; - call(topicURI: string, - payload?: any, - callbacks?: (() => void | SuccessErrorCallbacksHash), - advancedOptions?: CallAdvancedOptions): Wampy; - cancel(reqId: number, - callbacks?: (() => void | SuccessErrorCallbacksHash), - advancedOptions?: CancelAdvancedOptions): Wampy; - register(topicURI: string, callbacks: ((data: any) => any | RegisterCallbacksHash)): Wampy; - unregister(topicURI: string, callbacks?: (() => void | SuccessErrorCallbacksHash)): Wampy; -} - -interface WampyInstance { - new(url?: string, options?: WampyOptions): Wampy; -} - -declare var wampy: WampyInstance; - declare module "wampy" { + + interface WampyOptions { + autoReconnect?: boolean; + reconnectInterval?: number; + maxRetries?: number; + transportEncoding?: string; + realm?: string; + helloCustomDetails?: any; + onConnect?: () => void; + onClose?: () => void; + onError?: () => void; + onReconnect?: () => void; + ws?: any; + msgpackCoder?: any; + } + + interface WampyOpStatus { + code: number; + description: string; + reqId?: number; + } + + interface SuccessErrorCallbacksHash { + onSuccess?: (data: any) => void; + onError?: (err: string) => void; + } + + interface SubscribeCallbacksHash extends SuccessErrorCallbacksHash { + onEvent: (data: any) => void; + } + + interface RegisterCallbacksHash extends SuccessErrorCallbacksHash { + rpc: (data: any) => any; + } + + interface CallSuccessErrorCallbacksHash { + onSuccess: (data: any) => any; + onError?: (err: string) => void; + } + + interface AdvancedOptions { + exclude?: number | number[]; + eligible?: number | number[]; + exclude_me?: boolean; + disclose_me?: boolean; + } + + interface CallAdvancedOptions extends AdvancedOptions { + receive_progress?: boolean; + } + + interface CancelAdvancedOptions { + mode?: "skip" | "kill" | "killnowait"; + } + + interface Wampy { + options(opts?: WampyOptions): WampyOptions | Wampy; + getOpStatus(): WampyOpStatus; + getSessionId(): number; + connect(url?: string): Wampy; + disconnect(): Wampy; + abort(): Wampy; + subscribe(topicURI: string, callbacks: (((data: any) => void) | SubscribeCallbacksHash)): Wampy; + unsubscribe(topicURI: string, callbacks?: (((data: any) => void) | SubscribeCallbacksHash)): Wampy; + publish(topicURI: string, + payload?: any, + callbacks?: SuccessErrorCallbacksHash, + advancedOptions?: AdvancedOptions): Wampy; + call(topicURI: string, + payload?: any, + callbacks?: (((data: any) => void) | CallSuccessErrorCallbacksHash), + advancedOptions?: CallAdvancedOptions): Wampy; + cancel(reqId: number, + callbacks?: ((() => void) | SuccessErrorCallbacksHash), + advancedOptions?: CancelAdvancedOptions): Wampy; + register(topicURI: string, callbacks: (((data: any) => any) | RegisterCallbacksHash)): Wampy; + unregister(topicURI: string, callbacks?: ((() => void) | SuccessErrorCallbacksHash)): Wampy; + } + + interface WampyInstance { + new(url?: string, options?: WampyOptions): Wampy; + } + + var wampy: WampyInstance; + export = wampy; } From b1880a7db77887abd7ae9dda19f6c8b0e1a3530c Mon Sep 17 00:00:00 2001 From: vvakame Date: Mon, 28 Mar 2016 23:42:45 +0900 Subject: [PATCH 28/53] improve i18next-sprintf-postprocessor/i18next-sprintf-postprocessor.d.ts --- .../i18next-sprintf-postprocessor-tests.ts | 21 +++++++++--- .../i18next-sprintf-postprocessor.d.ts | 33 ++++++++++--------- i18next/i18next-2.0.17.d.ts | 3 -- 3 files changed, 35 insertions(+), 22 deletions(-) diff --git a/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor-tests.ts b/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor-tests.ts index b2bdf3b8d..36a948d62 100644 --- a/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor-tests.ts +++ b/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor-tests.ts @@ -1,10 +1,23 @@ -/// +/// import * as i18next from "i18next"; -import sprintf from "i18next-sprintf-postprocessor"; +import * as sprintfA from "i18next-sprintf-postprocessor"; +import sprintfB from "i18next-sprintf-postprocessor/dist/commonjs"; function initTest() { const i18nextOptions = {}; - i18next.use(sprintf).init(i18nextOptions); - i18next.init({ overloadTranslationOptionHandler: sprintf.overloadTranslationOptionHandler }); + i18next + .use(sprintfA) + .use(sprintfB) + .init(i18nextOptions); + i18next + .init({ overloadTranslationOptionHandler: sprintfA.overloadTranslationOptionHandler }); + i18next + .init({ overloadTranslationOptionHandler: sprintfB.overloadTranslationOptionHandler }); +} + +function tTest() { + i18next.t('interpolationTest1', 'a', 'b', 'c', 'd'); + i18next.t('interpolationTest3', 'z'); + i18next.t('interpolationTest4', 0); } diff --git a/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor.d.ts b/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor.d.ts index a069e45ff..1c0cf25ab 100644 --- a/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor.d.ts +++ b/i18next-sprintf-postprocessor/i18next-sprintf-postprocessor.d.ts @@ -3,29 +3,32 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// declare namespace I18next { - interface I18nextOptions extends i18nextSprintfPostProcessor.I18nextOptions {} -} - -declare namespace i18nextSprintfPostProcessor { - interface I18nextOptions { - overloadTranslationOptionHandler?(args: Array): void; - process?(value: any, key: string, options: Object): void; - } + interface I18n { + t(key: string, ...args: any[]): string; + } } declare module "i18next-sprintf-postprocessor" { import i18next = require("i18next"); - interface i18nextSprintfPostProcessor { - (): any; - process(value: any, key: string, options: Object): void; - overloadTranslationOptionHandler(args: Array): void; + interface I18nextSprintfPostProcessor { + name: string; + type: string; + process(value: any, key: string, options: any): any; + overloadTranslationOptionHandler(args: string[]): { + postProcess: "sprintf", + sprintf: string[] + }; } - var sprintf: i18nextSprintfPostProcessor; + var sprintf: I18nextSprintfPostProcessor; + export = sprintf; +} + +declare module "i18next-sprintf-postprocessor/dist/commonjs" { + import sprintf = require("i18next-sprintf-postprocessor"); export default sprintf; } diff --git a/i18next/i18next-2.0.17.d.ts b/i18next/i18next-2.0.17.d.ts index c8f803f05..61cff428a 100644 --- a/i18next/i18next-2.0.17.d.ts +++ b/i18next/i18next-2.0.17.d.ts @@ -5,10 +5,7 @@ // Sources: https://github.com/jamuhl/i18next/ -/// /// -/// -/// declare namespace I18next { export interface I18nextStatic {} From 7228f5ce05c3fc2dd7dd4a5b5cb1635bd226c4f1 Mon Sep 17 00:00:00 2001 From: Konstantin Burkalev Date: Mon, 28 Mar 2016 18:07:11 +0300 Subject: [PATCH 29/53] Fixes for es6 compilation --- wampy/wampy-tests.ts | 2 +- wampy/wampy.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/wampy/wampy-tests.ts b/wampy/wampy-tests.ts index eeea0132d..f7dcf9fe5 100644 --- a/wampy/wampy-tests.ts +++ b/wampy/wampy-tests.ts @@ -1,7 +1,7 @@ /// /// -import Wampy = require('wampy'); +import Wampy from 'wampy'; var ws = new Wampy('http://wamp.router.url', {realm: 'WAMPRealm'}); diff --git a/wampy/wampy.d.ts b/wampy/wampy.d.ts index 4c94eb0dd..650a8a91a 100644 --- a/wampy/wampy.d.ts +++ b/wampy/wampy.d.ts @@ -89,5 +89,5 @@ declare module "wampy" { var wampy: WampyInstance; - export = wampy; + export default wampy; } From 04a46a81d9ff12504800e02396189b1d2dc55171 Mon Sep 17 00:00:00 2001 From: Timothy Soehnlin Date: Mon, 28 Mar 2016 10:14:49 -0500 Subject: [PATCH 30/53] Update mongodb.d.ts Making initializedUnordered return UnorderedBulkOperation --- mongodb/mongodb.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index 90561b697..6c9f8efe7 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -642,7 +642,7 @@ declare module "mongodb" { //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp initializeOrderedBulkOp(options: CollectionOptions): OrderedBulkOperation; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp - initializeUnorderedBulkOp(options: CollectionOptions): OrderedBulkOperation; + initializeUnorderedBulkOp(options: CollectionOptions): UnorderedBulkOperation; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#insertMany insertMany(docs: Object[], callback: MongoCallback): void insertMany(docs: Object[], options?: CollectionInsertManyOptions): Promise; From e49f2982f06c276e08ec8444edd2f3bec1784aca Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 15 Feb 2016 20:12:57 +0500 Subject: [PATCH 31/53] lodash: changed _.noConflict --- lodash/lodash-3.10-tests.ts | 23 +++++++++++++++++------ lodash/lodash-3.10.d.ts | 7 +++++++ lodash/lodash-tests.ts | 23 +++++++++++++++++------ lodash/lodash.d.ts | 7 +++++++ 4 files changed, 48 insertions(+), 12 deletions(-) diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 8d19f394a..e780cf088 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -10270,12 +10270,23 @@ namespace TestMixin { } // _.noConflict -{ - let result: typeof _; - result = _.noConflict(); - result = _(42).noConflict(); - result = _([]).noConflict(); - result = _({}).noConflict(); +namespace TestNoConflict { + { + let result: typeof _; + + result = _.noConflict(); + result = _(42).noConflict(); + result = _([]).noConflict(); + result = _({}).noConflict(); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(42).chain().noConflict(); + result = _([]).chain().noConflict(); + result = _({}).chain().noConflict(); + } } // _.noop diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index c2fb9f726..47bc4e0c9 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -15430,6 +15430,13 @@ declare module _ { noConflict(): typeof _; } + interface LoDashExplicitWrapperBase { + /** + * @see _.noConflict + */ + noConflict(): LoDashExplicitObjectWrapper; + } + //_.noop interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index c8c824bd7..8435ff8e9 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -11506,12 +11506,23 @@ namespace TestMixin { } // _.noConflict -{ - let result: typeof _; - result = _.noConflict(); - result = _(42).noConflict(); - result = _([]).noConflict(); - result = _({}).noConflict(); +namespace TestNoConflict { + { + let result: typeof _; + + result = _.noConflict(); + result = _(42).noConflict(); + result = _([]).noConflict(); + result = _({}).noConflict(); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(42).chain().noConflict(); + result = _([]).chain().noConflict(); + result = _({}).chain().noConflict(); + } } // _.noop diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 790107369..d0544bc4c 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -18614,6 +18614,13 @@ declare module _ { noConflict(): typeof _; } + interface LoDashExplicitWrapperBase { + /** + * @see _.noConflict + */ + noConflict(): LoDashExplicitObjectWrapper; + } + //_.noop interface LoDashStatic { /** From 28900a5be9619820a7cdca817954b5aafc0e84ea Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 16 Feb 2016 19:49:11 +0500 Subject: [PATCH 32/53] lodash: changed _.sample --- lodash/lodash-3.10-tests.ts | 79 +++++++++++++-- lodash/lodash-3.10.d.ts | 185 ++++++++++++++++++++++++++---------- lodash/lodash-tests.ts | 101 ++++++++++++++++++-- lodash/lodash.d.ts | 160 +++++++++++++++++++++++-------- 4 files changed, 421 insertions(+), 104 deletions(-) diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 8d19f394a..3687c3209 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -5003,13 +5003,6 @@ namespace TestReject { } } -result = _.sample([1, 2, 3, 4]); -result = _.sample([1, 2, 3, 4], 2); -result = <_.LoDashImplicitWrapper>_([1, 2, 3, 4]).sample(); -result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3, 4]).sample(2); -result = _([1, 2, 3, 4]).sample().value(); -result = _([1, 2, 3, 4]).sample(2).value(); - // _.select namespace TestSelect { let array: TResult[]; @@ -5108,6 +5101,78 @@ namespace TestSelect { } } +// _.sample +namespace TestSample { + let array: string[]; + let list: _.List; + let dictionary: _.Dictionary; + let numericDictionary: _.NumericDictionary; + + { + let result: string; + + result = _.sample('abc'); + result = _.sample(array); + result = _.sample(list); + result = _.sample(dictionary); + result = _.sample(numericDictionary); + result = _.sample<{a: string}, string>({a: 'foo'}); + result = _.sample({a: 'foo'}); + + result = _('abc').sample(); + result = _(array).sample(); + result = _(list).sample(); + result = _(dictionary).sample(); + result = _(numericDictionary).sample(); + result = _({a: 'foo'}).sample(); + } + + { + let result: string[]; + + result = _.sample('abc', 42); + result = _.sample(array, 42); + result = _.sample(list, 42); + result = _.sample(dictionary, 42); + result = _.sample(numericDictionary, 42); + result = _.sample<{a: string}, string>({a: 'foo'}, 42); + result = _.sample({a: 'foo'}, 42); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('abc').sample(42); + result = _(array).sample(42); + result = _(list).sample(42); + result = _(dictionary).sample(42); + result = _(numericDictionary).sample(42); + result = _({a: 'foo'}).sample(42); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _('abc').chain().sample(); + result = _(array).chain().sample<_.LoDashExplicitWrapper>(); + result = _(list).chain().sample<_.LoDashExplicitWrapper>(); + result = _(dictionary).chain().sample<_.LoDashExplicitWrapper>(); + result = _(numericDictionary).chain().sample<_.LoDashExplicitWrapper>(); + result = _({a: 'foo'}).chain().sample<_.LoDashExplicitWrapper>(); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _('abc').chain().sample(42); + result = _(array).chain().sample(42); + result = _(list).chain().sample(42); + result = _(dictionary).chain().sample(42); + result = _(numericDictionary).chain().sample(42); + result = _({a: 'foo'}).chain().sample(42); + } +} + // _.shuffle namespace TestShuffle { let array: TResult[]; diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index c2fb9f726..939180145 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -8008,56 +8008,6 @@ declare module _ { reject(predicate: W): LoDashExplicitArrayWrapper; } - //_.sample - interface LoDashStatic { - /** - * Retrieves a random element or n random elements from a collection. - * @param collection The collection to sample. - * @return Returns the random sample(s) of collection. - **/ - sample(collection: Array): T; - - /** - * @see _.sample - **/ - sample(collection: List): T; - - /** - * @see _.sample - **/ - sample(collection: Dictionary): T; - - /** - * @see _.sample - * @param n The number of elements to sample. - **/ - sample(collection: Array, n: number): T[]; - - /** - * @see _.sample - * @param n The number of elements to sample. - **/ - sample(collection: List, n: number): T[]; - - /** - * @see _.sample - * @param n The number of elements to sample. - **/ - sample(collection: Dictionary, n: number): T[]; - } - - interface LoDashImplicitArrayWrapper { - /** - * @see _.sample - **/ - sample(n: number): LoDashImplicitArrayWrapper; - - /** - * @see _.sample - **/ - sample(): LoDashImplicitWrapper; - } - //_.select interface LoDashStatic { /** @@ -8217,6 +8167,141 @@ declare module _ { select(predicate: W): LoDashExplicitArrayWrapper; } + //_.sample + interface LoDashStatic { + /** + * Gets a random element or n random elements from a collection. + * + * @param collection The collection to sample. + * @return Returns the random sample(s) of collection. + */ + sample( + collection: List|Dictionary|NumericDictionary, + n: number + ): T[]; + + /** + * @see _.sample + */ + sample( + collection: O, + n: number + ): T[]; + + /** + * @see _.sample + */ + sample( + collection: Object, + n: number + ): T[]; + + /** + * @see _.sample + */ + sample( + collection: List|Dictionary|NumericDictionary + ): T; + + /** + * @see _.sample + */ + sample( + collection: O + ): T; + + /** + * @see _.sample + */ + sample( + collection: Object + ): T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sample + */ + sample( + n: number + ): LoDashImplicitArrayWrapper; + + /** + * @see _.sample + */ + sample(): string; + } + + interface LoDashImplicitArrayWrapper { + /** + * @see _.sample + */ + sample( + n: number + ): LoDashImplicitArrayWrapper; + + /** + * @see _.sample + */ + sample(): T; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.sample + */ + sample( + n: number + ): LoDashImplicitArrayWrapper; + + /** + * @see _.sample + */ + sample(): T; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sample + */ + sample( + n: number + ): LoDashExplicitArrayWrapper; + + /** + * @see _.sample + */ + sample(): LoDashExplicitWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.sample + */ + sample( + n: number + ): LoDashExplicitArrayWrapper; + + /** + * @see _.sample + */ + sample(): TWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.sample + */ + sample( + n: number + ): LoDashExplicitArrayWrapper; + + /** + * @see _.sample + */ + sample(): TWrapper; + } + //_.shuffle interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index c8c824bd7..b5838930c 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -5042,14 +5042,103 @@ namespace TestReject { } // _.sample -result = _.sample([1, 2, 3, 4]); -result = <_.LoDashImplicitWrapper>_([1, 2, 3, 4]).sample(); -result = _([1, 2, 3, 4]).sample().value(); +namespace TestSample { + let array: string[]; + let list: _.List; + let dictionary: _.Dictionary; + let numericDictionary: _.NumericDictionary; + + { + let result: string; + + result = _.sample('abc'); + result = _.sample(array); + result = _.sample(list); + result = _.sample(dictionary); + result = _.sample(numericDictionary); + result = _.sample<{a: string}, string>({a: 'foo'}); + result = _.sample({a: 'foo'}); + + result = _('abc').sample(); + result = _(array).sample(); + result = _(list).sample(); + result = _(dictionary).sample(); + result = _(numericDictionary).sample(); + result = _({a: 'foo'}).sample(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _('abc').chain().sample(); + result = _(array).chain().sample<_.LoDashExplicitWrapper>(); + result = _(list).chain().sample<_.LoDashExplicitWrapper>(); + result = _(dictionary).chain().sample<_.LoDashExplicitWrapper>(); + result = _(numericDictionary).chain().sample<_.LoDashExplicitWrapper>(); + result = _({a: 'foo'}).chain().sample<_.LoDashExplicitWrapper>(); + } +} // _.sampleSize -result = _.sampleSize([1, 2, 3, 4], 2); -result = <_.LoDashImplicitArrayWrapper>_([1, 2, 3, 4]).sampleSize(2); -result = _([1, 2, 3, 4]).sampleSize(2).value(); +namespace TestSampleSize { + let array: string[]; + let list: _.List; + let dictionary: _.Dictionary; + let numericDictionary: _.NumericDictionary; + + { + let result: string[]; + + result = _.sampleSize('abc'); + result = _.sampleSize('abc', 42); + result = _.sampleSize(array); + result = _.sampleSize(array, 42); + result = _.sampleSize(list); + result = _.sampleSize(list, 42); + result = _.sampleSize(dictionary); + result = _.sampleSize(dictionary, 42); + result = _.sampleSize(numericDictionary); + result = _.sampleSize(numericDictionary, 42); + result = _.sampleSize<{a: string}, string>({a: 'foo'}); + result = _.sampleSize<{a: string}, string>({a: 'foo'}, 42); + result = _.sampleSize({a: 'foo'}); + result = _.sampleSize({a: 'foo'}, 42); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('abc').sampleSize(); + result = _('abc').sampleSize(42); + result = _(array).sampleSize(); + result = _(array).sampleSize(42); + result = _(list).sampleSize(); + result = _(list).sampleSize(42); + result = _(dictionary).sampleSize(); + result = _(dictionary).sampleSize(42); + result = _(numericDictionary).sampleSize(); + result = _(numericDictionary).sampleSize(42); + result = _({a: 'foo'}).sampleSize(); + result = _({a: 'foo'}).sampleSize(42); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _('abc').chain().sampleSize(); + result = _('abc').chain().sampleSize(42); + result = _(array).chain().sampleSize(); + result = _(array).chain().sampleSize(42); + result = _(list).chain().sampleSize(); + result = _(list).chain().sampleSize(42); + result = _(dictionary).chain().sampleSize(); + result = _(dictionary).chain().sampleSize(42); + result = _(numericDictionary).chain().sampleSize(); + result = _(numericDictionary).chain().sampleSize(42); + result = _({a: 'foo'}).chain().sampleSize(); + result = _({a: 'foo'}).chain().sampleSize(42); + } +} // _.shuffle namespace TestShuffle { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 790107369..c7db5478e 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -8981,77 +8981,155 @@ declare module _ { //_.sample interface LoDashStatic { /** - * Gets a random element from `collection`. + * Gets a random element from collection. * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 + * @param collection The collection to sample. + * @return Returns the random element. */ - sample(collection: Array): T; + sample( + collection: List|Dictionary|NumericDictionary + ): T; /** - * @see _.sample - **/ - sample(collection: List): T; + * @see _.sample + */ + sample( + collection: O + ): T; /** - * @see _.sample - **/ - sample(collection: Dictionary): T; + * @see _.sample + */ + sample( + collection: Object + ): T; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sample + */ + sample(): string; } interface LoDashImplicitArrayWrapper { /** * @see _.sample - **/ - sample(): LoDashImplicitWrapper; + */ + sample(): T; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.sample + */ + sample(): T; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sample + */ + sample(): LoDashExplicitWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.sample + */ + sample(): TWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.sample + */ + sample(): TWrapper; } //_.sampleSize interface LoDashStatic { /** - * Gets `n` random elements from `collection`. + * Gets n random elements at unique keys from collection up to the size of collection. * - * @static - * @memberOf _ - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=0] The number of elements to sample. - * @returns {Array} Returns the random elements. - * @example - * - * _.sampleSize([1, 2, 3, 4], 2); - * // => [3, 1] + * @param collection The collection to sample. + * @param n The number of elements to sample. + * @return Returns the random elements. */ - sampleSize(collection: Array, n: number): T[]; + sampleSize( + collection: List|Dictionary|NumericDictionary, + n?: number + ): T[]; /** - * @see _.sampleSize - **/ - sampleSize(collection: List, n: number): T[]; + * @see _.sampleSize + */ + sampleSize( + collection: O, + n?: number + ): T[]; /** - * @see _.sampleSize - **/ - sampleSize(collection: Dictionary, n: number): T[]; + * @see _.sampleSize + */ + sampleSize( + collection: Object, + n?: number + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sampleSize + */ + sampleSize( + n?: number + ): LoDashImplicitArrayWrapper; } interface LoDashImplicitArrayWrapper { /** * @see _.sampleSize - **/ - sampleSize(n: number): LoDashImplicitArrayWrapper; + */ + sampleSize( + n?: number + ): LoDashImplicitArrayWrapper; + } + interface LoDashImplicitObjectWrapper { /** * @see _.sampleSize - **/ - sampleSize(): LoDashImplicitWrapper; + */ + sampleSize( + n?: number + ): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sampleSize + */ + sampleSize( + n?: number + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.sampleSize + */ + sampleSize( + n?: number + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.sampleSize + */ + sampleSize( + n?: number + ): LoDashExplicitArrayWrapper; } //_.shuffle From 8c52cc8aa17382ac5a47c7b16a4f96ee7a25eba0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladimir=20=C4=90oki=C4=87?= Date: Mon, 28 Mar 2016 22:43:14 +0200 Subject: [PATCH 33/53] Refactor interface names. Move interfaces into Jsen "ghost" module. Refactor tests. --- jsen/jsen-tests.ts | 71 ++++++++++++++-------------------------- jsen/jsen.d.ts | 81 +++++++++++++++++++++++++--------------------- 2 files changed, 69 insertions(+), 83 deletions(-) diff --git a/jsen/jsen-tests.ts b/jsen/jsen-tests.ts index 54dbd8ae9..9957a0120 100644 --- a/jsen/jsen-tests.ts +++ b/jsen/jsen-tests.ts @@ -1,5 +1,8 @@ /// +import jsen = require("jsen"); +import JsenSettings = Jsen.JsenSettings; + // any { // passes validation on any type @@ -372,10 +375,8 @@ { default: Math.PI } ]; - let validate: IJsenValidator; - schemas.forEach((schema) => { - validate = jsen(schema); + let validate = jsen(schema); console.assert(validate.build() === schema.default); }); } @@ -389,12 +390,9 @@ { default: new Date('05/14/2015') } ]; - let validate: IJsenValidator; - let def: any; - schemas.forEach((schema) => { - validate = jsen(schema); - def = validate.build(); + let validate = jsen(schema); + let def = validate.build(); console.assert(def !== schema.default); console.assert(JSON.stringify(def) === JSON.stringify(schema.default)); @@ -590,10 +588,8 @@ [null, {}, 'baz', false] ]; - let validate: IJsenValidator; - schemas.forEach((schema, index) => { - validate = jsen(schema); + let validate = jsen(schema); console.assert(JSON.stringify(validate.build(defaults[index])) === JSON.stringify(expected[index])); }); } @@ -1322,12 +1318,9 @@ ['b'] ]; - let validate: IJsenValidator; - let valid: boolean; - schemas.forEach((schema, index) => { - validate = jsen(schema); - valid = validate(data[index]); + let validate = jsen(schema); + let valid = validate(data[index]); console.assert(!valid); @@ -1362,12 +1355,9 @@ ['dependencies'] ]; - let validate: IJsenValidator; - let valid: boolean; - schemas.forEach((schema, index) => { - validate = jsen(schema); - valid = validate(data[index]); + let validate = jsen(schema); + let valid = validate(data[index]); console.assert(!valid); @@ -1560,13 +1550,10 @@ 'c is invalid' ]; - let validate: IJsenValidator; - let valid: boolean; - schemas.forEach((schema, index) => { //it(expectedMessages[index], function () { - validate = jsen(schema); - valid = validate(data[index]); + let validate = jsen(schema); + let valid = validate(data[index]); console.assert(!valid); console.assert(validate.errors.length === 1); @@ -1764,13 +1751,9 @@ schemas[24].messages.not ]; - let validate: IJsenValidator; - let valid: boolean; - schemas.forEach((schema: any, index: number) => { - validate = jsen(schema); - - valid = validate(data[index]); + let validate = jsen(schema); + let valid = validate(data[index]); console.assert(!valid); console.assert(validate.errors[validate.errors.length - 1].message === expectedMessages[index]); @@ -1971,14 +1954,11 @@ const doesNotThrow = (func: Function) => { } }; - let validate: IJsenValidator; - console.assert(doesNotThrow(() => { - validate = jsen(schema); + let validate = jsen(schema); + console.assert(validate({ 123: true })); }) ); - - console.assert(validate({ 123: true })); } // Fix cannot dereference schema when ids change resolution scope (#14) @@ -1993,15 +1973,14 @@ const doesNotThrow = (func: Function) => { } }; - let validate: IJsenValidator; - console.assert(doesNotThrow(() => { - validate = jsen(schema); + let validate = jsen(schema); + + console.assert(validate('abc')); + console.assert(!validate(123)); }) ); - console.assert(validate('abc')); - console.assert(!validate(123)); schema = { $ref: '#child/definitions/subchild', @@ -2018,7 +1997,7 @@ const doesNotThrow = (func: Function) => { }; console.assert(doesThrow(() => { - validate = jsen(schema); + let validate = jsen(schema); }) ); } @@ -2261,7 +2240,7 @@ const doesNotThrow = (func: Function) => { { let schema = { format: 'custom' }, callCount = 0, - options = { + options = { formats: { custom: () => { callCount++; @@ -2298,7 +2277,7 @@ const doesNotThrow = (func: Function) => { maximum: 10 }, callCount = 0, - options = { + options = { formats: { custom: () => { callCount++; @@ -2334,7 +2313,7 @@ const doesNotThrow = (func: Function) => { }, format: 'passwordsMatch' }, - options = { + options = { formats: { passwordsMatch: (obj: any) => { callCount++; diff --git a/jsen/jsen.d.ts b/jsen/jsen.d.ts index e230818b8..19407c849 100644 --- a/jsen/jsen.d.ts +++ b/jsen/jsen.d.ts @@ -3,43 +3,50 @@ // Definitions by: Vladimir Đokić // Definitions: https://github.com/borisyankov/DefinitelyTyped -interface IJsenFormats { - [key: string]: string | RegExp | Function; +declare module Jsen { + + export interface JsenFormats { + [key: string]: string | RegExp | Function; + } + + export interface JsenSettings { + missing$Ref?: boolean; + greedy?: boolean; + formats?: JsenFormats; + schemas?: any; + } + + export interface JsenBuildSettings { + copy?: boolean; + additionalProperties?: boolean; + } + + export interface JsenValidator { + (data?: any): boolean; + build(initial?: any, options?: JsenBuildSettings): any; + errors: JsenValidateError[]; + } + + export interface JsenValidateError { + path: string; + keyword: string; + message?: string; + } + + export interface JsenUnique { + (array: any[]): boolean; + findIndex(array: any[], value: any, comparator: (obj1: any, obj2: any) => boolean): number; + } + + export interface JsenMain { + (schema?: any, options?: JsenSettings): JsenValidator; + clone(data: any): any; + equal(a: any, b: any): boolean; + unique: JsenUnique; + } } -interface IJsenSettings { - missing$Ref?: boolean; - greedy?: boolean; - formats?: IJsenFormats; - schemas?: any; +declare module "jsen" { + var _jsen: Jsen.JsenMain; + export = _jsen; } - -interface IJsenBuildSettings { - copy?: boolean; - additionalProperties?: boolean; -} - -interface IJsenValidator { - (data?: any): boolean; - build(initial?: any, options?: IJsenBuildSettings): any; - errors: IValidateError[]; -} - -interface IValidateError { - path: string; - keyword: string; - message?: string; -} - -interface IJsenUnique { - (array: any[]): boolean; - findIndex(array: any[], value: any, comparator: (obj1: any, obj2: any) => boolean): number; -} -interface IJsen { - (schema?: any, options?: IJsenSettings): IJsenValidator; - clone(data: any): any; - equal(a: any, b: any): boolean; - unique: IJsenUnique; -} - -declare var jsen: IJsen; From d402f9342763915c687053f33b94b01876d38573 Mon Sep 17 00:00:00 2001 From: Dominik Lenk Date: Tue, 29 Mar 2016 00:40:55 +0200 Subject: [PATCH 34/53] Add MediaStreamAudioDestinationNode --- webaudioapi/waa.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index c9467c461..0cdcdc016 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -188,6 +188,10 @@ interface MediaStreamAudioSourceNode extends AudioNode { } +interface MediaStreamAudioDestinationNode extends AudioNode { + stream: MediaStream; +} + interface AudioBuffer { copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; @@ -202,4 +206,5 @@ interface AudioContext { suspend(): Promise; resume(): Promise; close(): Promise; + createMediaStreamDestination(): MediaStreamAudioDestinationNode; } From bd2fc2e67233f722e6be1508d7da736e0e88cfe3 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Wed, 17 Feb 2016 20:31:18 +0500 Subject: [PATCH 35/53] lodash: changed _.memoize --- lodash/lodash-3.10-tests.ts | 46 +++++++++++++++++++++++++++---------- lodash/lodash-3.10.d.ts | 8 +++++++ lodash/lodash-tests.ts | 46 +++++++++++++++++++++++++++---------- lodash/lodash.d.ts | 8 +++++++ 4 files changed, 84 insertions(+), 24 deletions(-) diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 8d19f394a..1c094912b 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -6097,20 +6097,42 @@ namespace TestFlowRight { // _.memoize namespace TestMemoize { - var testMemoizedFunction: _.MemoizedFunction; - var cache = <_.MapCache>testMemoizedFunction.cache; - interface TestMemoizedResultFn extends _.MemoizedFunction { + { + let memoizedFunction: _.MemoizedFunction; + let cache: _.MapCache = memoizedFunction.cache; + } + + interface MemoizedResultFn extends _.MemoizedFunction { (a1: string, a2: number): boolean; } - var testMemoizeFn = (a1: string, a2: number) => a1.length > a2; - var testMemoizeResolverFn = (a1: string, a2: number) => a1 + a2; - var result: TestMemoizedResultFn; - result = _.memoize(testMemoizeFn); - result = _.memoize(testMemoizeFn, testMemoizeResolverFn); - result = _(testMemoizeFn).memoize().value(); - result = _(testMemoizeFn).memoize(testMemoizeResolverFn).value(); - result('foo', 1); - result.cache.get('foo1'); + + let memoizeFn: (a1: string, a2: number) => boolean; + let memoizeResolverFn: (a1: string, a2: number) => string; + + { + let result: MemoizedResultFn; + + result = _.memoize(memoizeFn); + result = _.memoize(memoizeFn, memoizeResolverFn); + + result('foo', 1); + result.cache.get('foo1'); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(memoizeFn).memoize(); + result = _(memoizeFn).memoize(memoizeResolverFn); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(memoizeFn).chain().memoize(); + result = _(memoizeFn).chain().memoize(memoizeResolverFn); + } + _.memoize.Cache = { delete: key => false, get: key => undefined, diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index c2fb9f726..5ba05dc47 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -9735,6 +9735,7 @@ declare module _ { * storing the result based on the arguments provided to the memoized function. By default, the first argument * provided to the memoized function is coerced to a string and used as the cache key. The func is invoked with * the this binding of the memoized function. + * * @param func The function to have its output memoized. * @param resolver The function to resolve the cache key. * @return Returns the new memoizing function. @@ -9752,6 +9753,13 @@ declare module _ { memoize(resolver?: Function): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.memoize + */ + memoize(resolver?: Function): LoDashExplicitObjectWrapper; + } + //_.modArgs interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index c8c824bd7..4772f1d33 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -5977,20 +5977,42 @@ namespace TestFlowRight { // _.memoize namespace TestMemoize { - var testMemoizedFunction: _.MemoizedFunction; - var cache = <_.MapCache>testMemoizedFunction.cache; - interface TestMemoizedResultFn extends _.MemoizedFunction { + { + let memoizedFunction: _.MemoizedFunction; + let cache: _.MapCache = memoizedFunction.cache; + } + + interface MemoizedResultFn extends _.MemoizedFunction { (a1: string, a2: number): boolean; } - var testMemoizeFn = (a1: string, a2: number) => a1.length > a2; - var testMemoizeResolverFn = (a1: string, a2: number) => a1 + a2; - var result: TestMemoizedResultFn; - result = _.memoize(testMemoizeFn); - result = _.memoize(testMemoizeFn, testMemoizeResolverFn); - result = _(testMemoizeFn).memoize().value(); - result = _(testMemoizeFn).memoize(testMemoizeResolverFn).value(); - result('foo', 1); - result.cache.get('foo1'); + + let memoizeFn: (a1: string, a2: number) => boolean; + let memoizeResolverFn: (a1: string, a2: number) => string; + + { + let result: MemoizedResultFn; + + result = _.memoize(memoizeFn); + result = _.memoize(memoizeFn, memoizeResolverFn); + + result('foo', 1); + result.cache.get('foo1'); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(memoizeFn).memoize(); + result = _(memoizeFn).memoize(memoizeResolverFn); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(memoizeFn).chain().memoize(); + result = _(memoizeFn).chain().memoize(memoizeResolverFn); + } + _.memoize.Cache = { delete: key => false, get: key => undefined, diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 790107369..8383f3234 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -10467,6 +10467,7 @@ declare module _ { * storing the result based on the arguments provided to the memoized function. By default, the first argument * provided to the memoized function is coerced to a string and used as the cache key. The func is invoked with * the this binding of the memoized function. + * * @param func The function to have its output memoized. * @param resolver The function to resolve the cache key. * @return Returns the new memoizing function. @@ -10484,6 +10485,13 @@ declare module _ { memoize(resolver?: Function): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.memoize + */ + memoize(resolver?: Function): LoDashExplicitObjectWrapper; + } + //_.overArgs (was _.modArgs) interface LoDashStatic { /** From 8527f0915ccb0f403b6c49a331410492d1dd6026 Mon Sep 17 00:00:00 2001 From: jpmnteiro Date: Tue, 29 Mar 2016 13:20:38 +0100 Subject: [PATCH 36/53] created typings for angular-media-queries module --- angular-media-queries/match-media-tests.ts | 55 ++++++++++++++++++++++ angular-media-queries/match-media.d.ts | 27 +++++++++++ 2 files changed, 82 insertions(+) create mode 100644 angular-media-queries/match-media-tests.ts create mode 100644 angular-media-queries/match-media.d.ts diff --git a/angular-media-queries/match-media-tests.ts b/angular-media-queries/match-media-tests.ts new file mode 100644 index 000000000..8b87dedb7 --- /dev/null +++ b/angular-media-queries/match-media-tests.ts @@ -0,0 +1,55 @@ +/// + +var myApp = angular.module('testModule', ['matchMedia']); + +myApp.controller('TestController', ($log: angular.ILogService, + $scope: angular.IScope, + screenSize: angular.matchmedia.IScreenSize) => { + + var fnCallback = (result: boolean) => { + $log.info(`Result: ${result}`); + } + + // '.is(...)' examples + var res = screenSize.is(["xs", "sm"]); + fnCallback(res); + + res = screenSize.is("xs, lg") + fnCallback(res); + + // '.on(...)' examples + + res = screenSize.on(["xs", "sm"], fnCallback); + fnCallback(res); + + res = screenSize.on("xs, lg", fnCallback); + fnCallback(res); + + res = screenSize.on(["xs", "sm"], fnCallback, $scope); + fnCallback(res); + + res = screenSize.on("xs, lg", fnCallback, $scope); + fnCallback(res); + + // '.onChange(...)' examples + + res = screenSize.onChange($scope, ["xs", "sm"], fnCallback); + fnCallback(res); + + res = screenSize.onChange($scope, "xs, lg", fnCallback); + fnCallback(res); + + // '.when(...)' examples + + res = screenSize.when(["xs", "sm"], fnCallback); + fnCallback(res); + + res = screenSize.when("xs, lg", fnCallback); + fnCallback(res); + + res = screenSize.when(["xs", "sm"], fnCallback, $scope); + fnCallback(res); + + res = screenSize.when("xs, lg", fnCallback, $scope); + fnCallback(res); +}); \ No newline at end of file diff --git a/angular-media-queries/match-media.d.ts b/angular-media-queries/match-media.d.ts new file mode 100644 index 000000000..7e4316069 --- /dev/null +++ b/angular-media-queries/match-media.d.ts @@ -0,0 +1,27 @@ +// Type definitions for Angular matchMedia 0.6.0 (angular.matchMedia module) +// Project: https://github.com/jacopotarantino/angular-match-media +// Definitions by: Joao Monteiro +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +declare namespace angular.matchmedia { + + interface IScreenSize { + + is(list: Array | string): boolean; + + // Executes the callback function on window resize with the match truthiness as the first argument. + // Returns the current match truthiness. + // The 'scope' parameter is optional. If it's not passed in, '$rootScope' is used. + on(list: Array | string, callback: (result: boolean) => void, scope?: angular.IScope): boolean; + + // Executes the callback function ONLY when the match differs from previous match. + // Returns the current match truthiness. + // The 'scope' parameter is required for cleanup reasons (destroy event). + onChange(scope: angular.IScope, list: Array | string, callback: (result: boolean) => void): boolean; + + // Executes the callback only when inside of the particular screensize. + // The 'scope' parameter is optional. If it's not passed in, '$rootScope' is used. + when(list: Array | string, callback: (result: boolean) => void, scope?: angular.IScope): boolean; + } +} \ No newline at end of file From 1604efc1659d9f3dfacd95e3779be4c5e16ca927 Mon Sep 17 00:00:00 2001 From: jpmnteiro Date: Tue, 29 Mar 2016 13:54:48 +0100 Subject: [PATCH 37/53] added missing `.isRetina` property --- angular-media-queries/match-media-tests.ts | 5 +++++ angular-media-queries/match-media.d.ts | 3 +++ 2 files changed, 8 insertions(+) diff --git a/angular-media-queries/match-media-tests.ts b/angular-media-queries/match-media-tests.ts index 8b87dedb7..a9331751a 100644 --- a/angular-media-queries/match-media-tests.ts +++ b/angular-media-queries/match-media-tests.ts @@ -10,6 +10,11 @@ myApp.controller('TestController', ($log: angular.ILogService, $log.info(`Result: ${result}`); } + // '.isRetina' examples + if(screenSize.isRetina) { + $log.info("Retina screen detected") + } + // '.is(...)' examples var res = screenSize.is(["xs", "sm"]); fnCallback(res); diff --git a/angular-media-queries/match-media.d.ts b/angular-media-queries/match-media.d.ts index 7e4316069..401c61f46 100644 --- a/angular-media-queries/match-media.d.ts +++ b/angular-media-queries/match-media.d.ts @@ -8,6 +8,9 @@ declare namespace angular.matchmedia { interface IScreenSize { + // Returns a value indicating if the current device has a retina screen + isRetina: boolean; + is(list: Array | string): boolean; // Executes the callback function on window resize with the match truthiness as the first argument. From 3ff4c66db0a8abe7b54bba18a034e4219c24d6a7 Mon Sep 17 00:00:00 2001 From: didlich Date: Tue, 29 Mar 2016 19:12:20 +0200 Subject: [PATCH 38/53] fix cordova file-transfer plugin - upload method same as in issue #5435 for download method --- cordova/cordova-tests.ts | 2 +- cordova/plugins/FileTransfer.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index d0e6e6889..7e97305a2 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -192,7 +192,7 @@ file.upload('cdvfile://localhost/persistent/path/to/downloads/', console.error('Failed with exception ' + err.exception); } }, - { headers: null, httpMethod: "PUT" }, + { headers: {"X-Email": "user@mail.com", 'X-Token': "asdf3w234"}, httpMethod: "PUT" }, true); file.abort(); diff --git a/cordova/plugins/FileTransfer.d.ts b/cordova/plugins/FileTransfer.d.ts index 140973cd5..40829668a 100644 --- a/cordova/plugins/FileTransfer.d.ts +++ b/cordova/plugins/FileTransfer.d.ts @@ -93,7 +93,7 @@ interface FileUploadOptions { /** Whether to upload the data in chunked streaming mode. Defaults to true. */ chunkedMode?: boolean; /** A map of header name/header values. Use an array to specify more than one value. */ - headers?: Object[]; + headers?: Object; } /** Optional parameters for download method. */ From e4d9cb3ce0995cde5e4300c6e349a5329d306fd1 Mon Sep 17 00:00:00 2001 From: sixinli Date: Tue, 29 Mar 2016 13:54:46 -0400 Subject: [PATCH 39/53] add additional type for `autoColumnSize` according to docs in: http://docs.handsontable.com/0.17.0/Options.html#autoColumnSize --- jquery-handsontable/jquery-handsontable.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jquery-handsontable/jquery-handsontable.d.ts b/jquery-handsontable/jquery-handsontable.d.ts index 48f1bf790..14a6ab1b6 100644 --- a/jquery-handsontable/jquery-handsontable.d.ts +++ b/jquery-handsontable/jquery-handsontable.d.ts @@ -280,7 +280,7 @@ declare namespace Handsontable { /** * Setting to true enables the autoColumnSize plugin, which makes sure each column gets enough space to show its content. */ - autoColumnSize?: boolean; + autoColumnSize?: boolean | Object; /** * Setting to true enables the observeChanges plugin, which automatically renders the table when a change in the data source is observed. From de24a81a5484a13e7be392c18361c129cf1b0d21 Mon Sep 17 00:00:00 2001 From: Ethan Breder Date: Tue, 29 Mar 2016 14:21:49 -0700 Subject: [PATCH 40/53] Add HTMLAttributes to CellProps Previously adding a className (or any other HTML attribute) to a Cell as a property would result in a compilation error. --- fixed-data-table/fixed-data-table-tests.tsx | 16 ++++++++-------- fixed-data-table/fixed-data-table.d.ts | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/fixed-data-table/fixed-data-table-tests.tsx b/fixed-data-table/fixed-data-table-tests.tsx index 2c8e04a7d..a5f1ab9f0 100644 --- a/fixed-data-table/fixed-data-table-tests.tsx +++ b/fixed-data-table/fixed-data-table-tests.tsx @@ -88,16 +88,16 @@ interface RowData { interface MyCellProps extends CellProps { rowIndex?: number; field: string; - data: RowData[]; + myData: RowData[]; } class MyTextCell extends React.Component { render(): React.ReactElement { - const {rowIndex, field, data} = this.props; + const {rowIndex, field, myData} = this.props; return ( - - {data[rowIndex][field]} + + {myData[rowIndex][field]} ); } @@ -105,11 +105,11 @@ class MyTextCell extends React.Component { class MyLinkCell extends React.Component { render(): React.ReactElement { - const {rowIndex, field, data} = this.props; - const link: string = data[rowIndex][field]; + const {rowIndex, field, myData} = this.props; + const link: string = myData[rowIndex][field]; return ( - + {link} ); @@ -150,7 +150,7 @@ class MyTable4 extends React.Component<{}, MyTable4State> { header={{field}} cell={ } diff --git a/fixed-data-table/fixed-data-table.d.ts b/fixed-data-table/fixed-data-table.d.ts index b4e404a57..e4bc79ff5 100644 --- a/fixed-data-table/fixed-data-table.d.ts +++ b/fixed-data-table/fixed-data-table.d.ts @@ -458,11 +458,11 @@ declare namespace FixedDataTable { * /> * ); */ - export interface CellProps { + export interface CellProps extends __React.HTMLAttributes { /** * The row index of the cell. */ - rowIndex?: number + rowIndex?: number; /** * Outer height of the cell. From 1ec036686e70ad0d837ed2443684d54bca13af01 Mon Sep 17 00:00:00 2001 From: Sean Kelley Date: Tue, 29 Mar 2016 15:03:48 -0700 Subject: [PATCH 41/53] Make moment's typings for parsing stricter and also allow them to accept union types. These changes do two things. 1. Replace very lax typings like `any[]` with stricter, more-correct versions. In particular, the ISO_8601 constant, while /technically/ a void function, is actually an opaque sentinel that a consumer should not know anything about it. The function type was replaced with a sentinel type using the principle of "brands" that can be seen in the Typescript compiler: https://github.com/Microsoft/TypeScript/blob/413d9a639f933df7539070b236c1677de8302a93/src/compiler/types.ts#L9 2. Replace the many overloads of the parsing methods with a smaller representative set that uses union types instead. Aside from succinctness, this allows callers to provide a union type as the argument, as long as it matches, which was not possible before (Typescript does not explode the union type to see if overloads cover all the possibilities). --- moment-timezone/moment-timezone.d.ts | 20 ++++---------------- moment/moment-node.d.ts | 18 +++++++++--------- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/moment-timezone/moment-timezone.d.ts b/moment-timezone/moment-timezone.d.ts index 85d5b4707..c1d7e2d23 100644 --- a/moment-timezone/moment-timezone.d.ts +++ b/moment-timezone/moment-timezone.d.ts @@ -35,22 +35,10 @@ interface MomentTimezone { (date: number, timezone: string): moment.Moment; (date: number[], timezone: string): moment.Moment; (date: string, timezone: string): moment.Moment; - (date: string, format: string, timezone: string): moment.Moment; - (date: string, format: string, strict: boolean, timezone: string): moment.Moment; - (date: string, format: string, language: string, timezone: string): moment.Moment; - (date: string, format: string, language: string, strict: boolean, timezone: string): moment.Moment; - (date: string, formats: string[], timezone: string): moment.Moment; - (date: string, formats: string[], strict: boolean, timezone: string): moment.Moment; - (date: string, formats: string[], language: string, timezone: string): moment.Moment; - (date: string, formats: string[], language: string, strict: boolean, timezone: string): moment.Moment; - (date: string, specialFormat: () => void, timezone: string): moment.Moment; - (date: string, specialFormat: () => void, strict: boolean, timezone: string): moment.Moment; - (date: string, specialFormat: () => void, language: string, timezone: string): moment.Moment; - (date: string, specialFormat: () => void, language: string, strict: boolean, timezone: string): moment.Moment; - (date: string, formatsIncludingSpecial: any[], timezone: string): moment.Moment; - (date: string, formatsIncludingSpecial: any[], strict: boolean, timezone: string): moment.Moment; - (date: string, formatsIncludingSpecial: any[], language: string, timezone: string): moment.Moment; - (date: string, formatsIncludingSpecial: any[], language: string, strict: boolean, timezone: string): moment.Moment; + (date: string, format: moment.MomentFormatSpecification, timezone: string): moment.Moment; + (date: string, format: moment.MomentFormatSpecification, strict: boolean, timezone: string): moment.Moment; + (date: string, format: moment.MomentFormatSpecification, language: string, timezone: string): moment.Moment; + (date: string, format: moment.MomentFormatSpecification, language: string, strict: boolean, timezone: string): moment.Moment; (date: Date, timezone: string): moment.Moment; (date: moment.Moment, timezone: string): moment.Moment; (date: Object, timezone: string): moment.Moment; diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 13959bbf8..5199a64a2 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -571,6 +571,12 @@ declare namespace moment { yy: any; } + interface MomentBuiltinFormat { + __momentBuiltinFormatBrand: any; + } + + type MomentFormatSpecification = string | MomentBuiltinFormat | (string | MomentBuiltinFormat)[]; + interface MomentStatic { version: string; fn: Moment; @@ -578,14 +584,8 @@ declare namespace moment { (): Moment; (date: number): Moment; (date: number[]): Moment; - (date: string, format?: string, strict?: boolean): Moment; - (date: string, format?: string, language?: string, strict?: boolean): Moment; - (date: string, formats: string[], strict?: boolean): Moment; - (date: string, formats: string[], language?: string, strict?: boolean): Moment; - (date: string, specialFormat: () => void, strict?: boolean): Moment; - (date: string, specialFormat: () => void, language?: string, strict?: boolean): Moment; - (date: string, formatsIncludingSpecial: any[], strict?: boolean): Moment; - (date: string, formatsIncludingSpecial: any[], language?: string, strict?: boolean): Moment; + (date: string, format?: MomentFormatSpecification, strict?: boolean): Moment; + (date: string, format?: MomentFormatSpecification, language?: string, strict?: boolean): Moment; (date: Date): Moment; (date: Moment): Moment; (date: Object): Moment; @@ -675,7 +675,7 @@ declare namespace moment { /** * Constant used to enable explicit ISO_8601 format parsing. */ - ISO_8601(): void; + ISO_8601: MomentBuiltinFormat; defaultFormat: string; } From 4e9c574a8f3d41856990913966a7a226bb865443 Mon Sep 17 00:00:00 2001 From: Ryan McNamara Date: Tue, 29 Mar 2016 17:18:34 -0700 Subject: [PATCH 42/53] Updating ng-flow to add to the angular module This is more in line with what angularjs/angular.d.ts intends --- ng-flow/ng-flow.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ng-flow/ng-flow.d.ts b/ng-flow/ng-flow.d.ts index 564caaadc..fe5fad56a 100644 --- a/ng-flow/ng-flow.d.ts +++ b/ng-flow/ng-flow.d.ts @@ -3,8 +3,9 @@ // Definitions by: Ryan McNamara // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// -declare namespace ng.flow { +declare namespace angular.flow { interface IFlowFactory { create(options?: flowjs.IFlowOptions): flowjs.IFlow; } From 95d827df4b3b2091e6aa8d329d6a34cea03b4dc9 Mon Sep 17 00:00:00 2001 From: Kohei Hisakuni Date: Tue, 29 Mar 2016 20:45:22 -0700 Subject: [PATCH 43/53] Make callback required --- gapi/gapi.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gapi/gapi.d.ts b/gapi/gapi.d.ts index d1481d28c..9e4e603bb 100644 --- a/gapi/gapi.d.ts +++ b/gapi/gapi.d.ts @@ -141,7 +141,7 @@ declare namespace gapi.client { * @param version The version of the API to load * @param callback the function that is called once the API interface is loaded */ - export function load(name: string, version: string, callback?: () => any): void; + export function load(name: string, version: string, callback: () => any): void; /** * Creates a HTTP request for making RESTful requests. * An object encapsulating the various arguments for this method. From 984de2a7a75c49aed853ccddffcb50dafc72e382 Mon Sep 17 00:00:00 2001 From: rhysd Date: Wed, 30 Mar 2016 14:57:02 +0900 Subject: [PATCH 44/53] node.d.ts: Update "vm" module (node 5.9.1) https://nodejs.org/api/vm.html --- node/node.d.ts | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index f007940da..05ba25669 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -932,15 +932,34 @@ declare module "readline" { declare module "vm" { export interface Context { } - export interface Script { - runInThisContext(): void; - runInNewContext(sandbox?: Context): void; + export interface ScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData: boolean; } - export function runInThisContext(code: string, filename?: string): void; - export function runInNewContext(code: string, sandbox?: Context, filename?: string): void; - export function runInContext(code: string, context: Context, filename?: string): void; - export function createContext(initSandbox?: Context): Context; - export function createScript(code: string, filename?: string): Script; + export interface RunningScriptOptions { + filename?: string; + lineOffset?: number; + columnOffset?: number; + displayErrors?: boolean; + timeout?: number; + } + export class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + export function createContext(sandbox?: Context): Context; + export function isContext(sandbox: Context): boolean; + export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any; + export function runInDebugContext(code: string): any; + export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any; + export function runInThisContext(code: string, options?: RunningScriptOptions): any; } declare module "child_process" { From 13bc8b833723fc2d35531c091b894590a9199514 Mon Sep 17 00:00:00 2001 From: rhysd Date: Wed, 30 Mar 2016 14:57:52 +0900 Subject: [PATCH 45/53] node.d.ts: Create tests for "vm" module --- node/node-tests.ts | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/node/node-tests.ts b/node/node-tests.ts index 18c345118..e5a20fa78 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -16,6 +16,7 @@ import * as path from "path"; import * as readline from "readline"; import * as childProcess from "child_process"; import * as os from "os"; +import * as vm from "vm"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -679,3 +680,63 @@ namespace os_tests { result = os.networkInterfaces(); } } + +//////////////////////////////////////////////////// +/// vm tests : https://nodejs.org/api/vm.html +//////////////////////////////////////////////////// + +namespace vm_tests { + { + const sandbox = { + animal: 'cat', + count: 2 + }; + + const context = new vm.createContext(sandbox); + console.log(vm.isContext(context)); + const script = new vm.Script('count += 1; name = "kitty"'); + + for (let i = 0; i < 10; ++i) { + script.runInContext(context); + } + + console.log(util.inspect(sandbox)); + + vm.runInNewContext('count += 1; name = "kitty"', sandbox); + console.log(util.inspect(sandbox)); + } + + { + const sandboxes = [{}, {}, {}]; + + const script = new vm.Script('globalVar = "set"'); + + sandboxes.forEach((sandbox) => { + script.runInNewContext(sandbox); + }); + + console.log(util.inspect(sandboxes)); + } + + { + global.globalVar = 0; + + const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + + for (var i = 0; i < 1000; ++i) { + script.runInThisContext(); + } + + console.log(globalVar); + + var localVar = 'initial value'; + vm.runInThisContext('localVar = "vm";'); + + console.log(localVar); + } + + { + const Debug = vm.runInDebugContext('Debug'); + Debug.scripts().forEach(function(script) { console.log(script.name); }); + } +} From 292e56b5acdb2157c3f53d70a77d34d64ba5fe2f Mon Sep 17 00:00:00 2001 From: rhysd Date: Wed, 30 Mar 2016 15:47:09 +0900 Subject: [PATCH 46/53] node.d.ts: Fix errors reported by 'tsc --target es6 --noImplicitAny' --- node/node-tests.ts | 20 +++++--------------- node/node.d.ts | 2 +- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index e5a20fa78..66c4256ca 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -33,7 +33,8 @@ assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparat assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); assert.doesNotThrow(() => { - if (false) { throw "a hammer at your face"; } + const b = false; + if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); //////////////////////////////////////////////////// @@ -692,7 +693,7 @@ namespace vm_tests { count: 2 }; - const context = new vm.createContext(sandbox); + const context = vm.createContext(sandbox); console.log(vm.isContext(context)); const script = new vm.Script('count += 1; name = "kitty"'); @@ -713,21 +714,10 @@ namespace vm_tests { sandboxes.forEach((sandbox) => { script.runInNewContext(sandbox); + script.runInThisContext(); }); console.log(util.inspect(sandboxes)); - } - - { - global.globalVar = 0; - - const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); - - for (var i = 0; i < 1000; ++i) { - script.runInThisContext(); - } - - console.log(globalVar); var localVar = 'initial value'; vm.runInThisContext('localVar = "vm";'); @@ -737,6 +727,6 @@ namespace vm_tests { { const Debug = vm.runInDebugContext('Debug'); - Debug.scripts().forEach(function(script) { console.log(script.name); }); + Debug.scripts().forEach(function(script: any) { console.log(script.name); }); } } diff --git a/node/node.d.ts b/node/node.d.ts index 05ba25669..66e9a935f 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -939,7 +939,7 @@ declare module "vm" { displayErrors?: boolean; timeout?: number; cachedData?: Buffer; - produceCachedData: boolean; + produceCachedData?: boolean; } export interface RunningScriptOptions { filename?: string; From 2058a1951c4d23ca98d302cd00d51a0bcc528851 Mon Sep 17 00:00:00 2001 From: TANAKA Koichi Date: Wed, 30 Mar 2016 18:02:12 +0900 Subject: [PATCH 47/53] Add definition for password-hash npm: https://www.npmjs.com/package/password-hash project: https://github.com/davidwood/node-password-hash --- password-hash/password-hash-tests.ts | 18 ++++++++++++++++++ password-hash/password-hash.d.ts | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 password-hash/password-hash-tests.ts create mode 100644 password-hash/password-hash.d.ts diff --git a/password-hash/password-hash-tests.ts b/password-hash/password-hash-tests.ts new file mode 100644 index 000000000..a36db4e8b --- /dev/null +++ b/password-hash/password-hash-tests.ts @@ -0,0 +1,18 @@ +/// +'use strict'; + +import {generate, verify, isHashed} from 'password-hash'; + +let password = 'raw-password'; +let hashed: string; + +hashed = generate(password); +hashed = generate(password, {algorithm: 'sha256'}); +hashed = generate(password, {saltLength: 10}); +hashed = generate(password, {iterations: 11}); +hashed = generate(password, {algorithm: 'sha512', saltLength: 9, iterations: 11}); + +let isOk: boolean; + +isOk = verify(password, hashed); +isOk = isHashed(password); diff --git a/password-hash/password-hash.d.ts b/password-hash/password-hash.d.ts new file mode 100644 index 000000000..d2a90abdb --- /dev/null +++ b/password-hash/password-hash.d.ts @@ -0,0 +1,16 @@ +// Type definitions for password-hash 1.2.x +// Project: https://github.com/davidwood/node-password-hash +// Definitions by: TANAKA Koichi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'password-hash' { + export function generate(password: string, options?: Options): string; + export function verify(password: string, hashedPassword: string): boolean; + export function isHashed(password: string): boolean; + + export interface Options { + algorithm?: string; + saltLength?: number; + iterations?: number; + } +} From e42fc3e47141c1d94a7b776357f64940de33843e Mon Sep 17 00:00:00 2001 From: Giedrius Grabauskas Date: Wed, 30 Mar 2016 15:46:59 +0300 Subject: [PATCH 48/53] Updated react-router 2.0 Added onchange hook. Updated all hooks. Params changed from object to dictionary. Changed to use location descriptor. --- react-router/react-router.d.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index d42e7da46..357490e60 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -18,15 +18,23 @@ declare namespace ReactRouter { type Component = React.ReactType - type EnterHook = (nextState: RouterState, replaceState: RedirectFunction, callback?: Function) => any + type EnterHook = (nextState: RouterState, replace: RedirectFunction, callback?: Function) => void - type LeaveHook = () => any + type LeaveHook = () => void + + type ChangeHook = (prevState: RouterState, nextState: RouterState, replace: RedirectFunction, callback: Function) => void; - type Params = Object + type Params = { [param: string]: string } type ParseQueryString = (queryString: H.QueryString) => H.Query - type RedirectFunction = (state: H.LocationState, pathname: H.Pathname | H.Path, query?: H.Query) => void + interface RedirectFunction { + (location: H.LocationDescriptor): void; + /** + * @deprecated `replaceState(state, pathname, query) is deprecated; Use `replace(location)` with a location descriptor instead. http://tiny.cc/router-isActivedeprecated + */ + (state: H.LocationState, pathname: H.Pathname | H.Path, query?: H.Query): void; + } type RouteComponent = Component @@ -98,7 +106,7 @@ declare namespace ReactRouter { activeStyle?: React.CSSProperties activeClassName?: string onlyActiveOnIndex?: boolean - to: RoutePattern + to: RoutePattern | H.LocationDescriptor query?: H.Query state?: H.LocationState } @@ -138,6 +146,7 @@ declare namespace ReactRouter { getComponents?: (location: H.Location, cb: (error: any, components?: RouteComponents) => void) => void onEnter?: EnterHook onLeave?: LeaveHook + onChange?: ChangeHook getIndexRoute?: (location: H.Location, cb: (error: any, indexRoute: RouteConfig) => void) => void getChildRoutes?: (location: H.Location, cb: (error: any, childRoutes: RouteConfig) => void) => void } From 117ecb86cfdea98012d4de67d0ccd6b36e62183c Mon Sep 17 00:00:00 2001 From: SereznoKot Date: Wed, 30 Mar 2016 17:28:19 +0300 Subject: [PATCH 49/53] Fix material and geometry types of Points - Set type for material according to docs - Make geometry parameter in constructor optional, because three.js provides a default value - Make geometry type in constructor match one of the class member --- threejs/three.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 14d2c0b4e..e33b389ed 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -4539,18 +4539,18 @@ declare namespace THREE { export class Points extends Object3D { /** - * @param geometry An instance of Geometry. + * @param geometry An instance of Geometry or BufferGeometry. * @param material An instance of Material (optional). */ constructor( - geometry: Geometry | BufferGeometry, - material?: PointsMaterial | ShaderMaterial + geometry?: Geometry | BufferGeometry, + material?: Material ); /** - * An instance of Geometry, where each vertex designates the position of a particle in the system. + * An instance of Geometry or BufferGeometry, where each vertex designates the position of a particle in the system. */ - geometry: Geometry; + geometry: Geometry | BufferGeometry; /** * An instance of Material, defining the object's appearance. Default is a PointsMaterial with randomised colour. From 01fb3b9315ea18c22f61cd13ab56c60b9e99d415 Mon Sep 17 00:00:00 2001 From: Alex Pyzhianov Date: Wed, 30 Mar 2016 18:23:05 +0300 Subject: [PATCH 50/53] Fix EventDispatcher events, add Event interface - Remove target from dispatchEvent method, because only type is required to dispatch event and target field is inserted by three.js itself. https://github.com/mrdoob/three.js/blob/master/src/core/EventDispatcher.js - Add Event interface for callback argument in addEventListener, hasEventListener, removeEventListener --- threejs/three.d.ts | 69 +++++++++++++++++++++++++--------------------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 14d2c0b4e..04deadfb2 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -753,10 +753,10 @@ declare namespace THREE { dispose(): void; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; addIndex(index: any): void; // deprecated, use setIndex() addAttribute(name: any, array: any, itemSize: any): any; // deprecated @@ -860,10 +860,10 @@ declare namespace THREE { dispose(): void; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; } @@ -905,27 +905,32 @@ declare namespace THREE { * @param type The type of the listener that gets removed. * @param listener The listener function that gets removed. */ - addEventListener(type: string, listener: (event: any) => void ): void; + addEventListener(type: string, listener: (event: Event) => void ): void; /** * Adds a listener to an event type. * @param type The type of the listener that gets removed. * @param listener The listener function that gets removed. */ - hasEventListener(type: string, listener: (event: any) => void): void; + hasEventListener(type: string, listener: (event: Event) => void): void; /** * Removes a listener from an event type. * @param type The type of the listener that gets removed. * @param listener The listener function that gets removed. */ - removeEventListener(type: string, listener: (event: any) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; /** * Fire an event type. * @param type The type of event that gets fired. */ - dispatchEvent(event: { type: string; target: any; }): void; + dispatchEvent(event: { type: string; }): void; + } + + export interface Event { + type: string; + target: any; } /** @@ -1235,10 +1240,10 @@ declare namespace THREE { animations: AnimationClip[]; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; } export namespace GeometryUtils { // deprecated @@ -1611,10 +1616,10 @@ declare namespace THREE { copy(source: Object3D, recursive?: boolean): Object3D; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; getChildByName(name: string): Object3D; // deprecated, use getObjectByName() } @@ -2252,10 +2257,10 @@ declare namespace THREE { dispose(): void; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; } export interface LineBasicMaterialParameters extends MaterialParameters { @@ -4942,10 +4947,10 @@ declare namespace THREE { dispose(): void; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; } export class WebGLRenderTargetCube extends WebGLRenderTarget { @@ -5435,10 +5440,10 @@ declare namespace THREE { transformUv(uv: Vector): void; // EventDispatcher mixins - addEventListener(type: string, listener: (event: any) => void ): void; - hasEventListener(type: string, listener: (event: any) => void): void; - removeEventListener(type: string, listener: (event: any) => void): void; - dispatchEvent(event: { type: string; target: any; }): void; + addEventListener(type: string, listener: (event: Event) => void ): void; + hasEventListener(type: string, listener: (event: Event) => void): void; + removeEventListener(type: string, listener: (event: Event) => void): void; + dispatchEvent(event: { type: string; }): void; } export class CanvasTexture extends Texture { From 684bb45932fc225b5a42926c78f1c2a2845d248f Mon Sep 17 00:00:00 2001 From: TANAKA Koichi Date: Thu, 31 Mar 2016 01:39:49 +0900 Subject: [PATCH 51/53] Add definition for passport-jwt npm: https://www.npmjs.com/package/passport-jwt project: https://github.com/themikenicholson/passport-jwt --- passport-jwt/passport-jwt-tests.ts | 36 +++++++++++++++++++++ passport-jwt/passport-jwt.d.ts | 50 ++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 passport-jwt/passport-jwt-tests.ts create mode 100644 passport-jwt/passport-jwt.d.ts diff --git a/passport-jwt/passport-jwt-tests.ts b/passport-jwt/passport-jwt-tests.ts new file mode 100644 index 000000000..ea173f3e0 --- /dev/null +++ b/passport-jwt/passport-jwt-tests.ts @@ -0,0 +1,36 @@ +/// +/// +'use strict'; + +import {Strategy as JwtStrategy, ExtractJwt, StrategyOptions} from 'passport-jwt'; +import {Request} from 'express'; +import * as passport from 'passport'; + +let opts: StrategyOptions = { + jwtFromRequest: ExtractJwt.fromAuthHeader(), + secretOrKey: 'secret', + issuer: "accounts.example.com", + audience: "example.org" +}; + +passport.use(new JwtStrategy(opts, function(jwt_payload, done) { + findUser({id: jwt_payload.sub}, function(err, user) { + if (err) { + return done(err, false); + } + if (user) { + done(null, user); + } else { + done(null, false, {message: 'foo'}); + // or you could create a new account + } + }); +})); + +opts.jwtFromRequest = ExtractJwt.fromHeader('x-api-key'); +opts.jwtFromRequest = ExtractJwt.fromBodyField('field_name'); +opts.jwtFromRequest = ExtractJwt.fromUrlQueryParameter('param_name'); +opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('param_name'); +opts.jwtFromRequest = (req: Request) => { return req.query.token; }; + +declare function findUser(condition: {id: string}, callback: (error: any, user :any) => void): void; diff --git a/passport-jwt/passport-jwt.d.ts b/passport-jwt/passport-jwt.d.ts new file mode 100644 index 000000000..9f6d91cc4 --- /dev/null +++ b/passport-jwt/passport-jwt.d.ts @@ -0,0 +1,50 @@ +// Type definitions for passport-jwt 2.0 +// Project: https://github.com/themikenicholson/passport-jwt +// Definitions by: TANAKA Koichi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +/// + +declare module 'passport-jwt' { + import {Strategy as PassportStrategy} from 'passport-strategy'; + import {Request} from 'express'; + + export class Strategy extends PassportStrategy { + constructor(opt: StrategyOptions, verify: VerifyCallback); + constructor(opt: StrategyOptions, verify: VerifyCallbackWithRequest); + } + + export interface StrategyOptions { + secretOrKey: string; + jwtFromRequest: JwtFromRequestFunction; + issuer?: string; + audience?: string; + algorithms?: string[]; + ignoreExpiration?: boolean; + passReqToCallback?: boolean; + } + + export interface VerifyCallback { + (payload: any, done: VerifiedCallback): void; + } + + export interface VerifyCallbackWithRequest { + (req: Request, payload: any, done: VerifiedCallback): void; + } + + export interface VerifiedCallback { + (error: any, user?: any, info?: any): void; + } + + export interface JwtFromRequestFunction { + (req: Request): string; + } + + export namespace ExtractJwt { + export function fromHeader(header_name: string): JwtFromRequestFunction; + export function fromBodyField(field_name: string): JwtFromRequestFunction; + export function fromUrlQueryParameter(param_name: string): JwtFromRequestFunction; + export function fromAuthHeaderWithScheme(auth_scheme: string): JwtFromRequestFunction; + export function fromAuthHeader(): JwtFromRequestFunction; + } +} From 9c110cd0c3204fd62a4e9b1a52e4c0edf4bd201b Mon Sep 17 00:00:00 2001 From: Sam Verschueren Date: Wed, 30 Mar 2016 19:40:06 +0200 Subject: [PATCH 52/53] update query-string definition --- query-string/query-string-tests.ts | 1 + query-string/query-string.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/query-string/query-string-tests.ts b/query-string/query-string-tests.ts index 597d270f2..e27078600 100644 --- a/query-string/query-string-tests.ts +++ b/query-string/query-string-tests.ts @@ -4,6 +4,7 @@ import qs = require('query-string'); qs.stringify({ foo: 'bar' }); qs.stringify({ foo: 'bar', bar: 'baz' }); +qs.stringify({ foo: 'bar' }, {strict: false}) qs.parse('?foo=bar'); qs.parse('#foo=bar'); diff --git a/query-string/query-string.d.ts b/query-string/query-string.d.ts index e4d76d003..ebee7e81a 100644 --- a/query-string/query-string.d.ts +++ b/query-string/query-string.d.ts @@ -16,7 +16,7 @@ declare module "query-string" { * * @param obj */ - export function stringify(obj: any): string; + export function stringify(obj: any, options?: {strict: boolean}): string; /** * Extract a query string from a URL that can be passed into .parse(). From a44332a250f703db51a79b2befd635ca9f38b15c Mon Sep 17 00:00:00 2001 From: Chris Watson Date: Wed, 30 Mar 2016 20:47:41 -0700 Subject: [PATCH 53/53] Added ensureDirSync --- fs-extra-promise/fs-extra-promise.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/fs-extra-promise/fs-extra-promise.d.ts b/fs-extra-promise/fs-extra-promise.d.ts index 77de92934..2243a4d1c 100644 --- a/fs-extra-promise/fs-extra-promise.d.ts +++ b/fs-extra-promise/fs-extra-promise.d.ts @@ -166,7 +166,8 @@ declare module "fs-extra-promise" { export function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; export function exists(path: string, callback?: (exists: boolean) => void): void; export function existsSync(path: string): boolean; - export function ensureDir(path: string, cb: (err: Error) => void): void; + export function ensureDir(path: string, cb: (err: Error) => void): void; + export function ensureDirSync(path: string): void; export interface OpenOptions { encoding?: string;