Merge branch 'master' of github.com:borisyankov/DefinitelyTyped into angular-optional

This commit is contained in:
Paulo Cesar
2014-08-05 21:54:02 -03:00
38 changed files with 4849 additions and 477 deletions
+6
View File
@@ -31,6 +31,7 @@ All definitions files include a header with the author and editors, so at some p
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm))
* [big.js](https://github.com/MikeMcl/big.js) (by [Steve Ognibene](https://github.com/nycdotnet))
* [BigInt](https://github.com/Evgenus/BigInt) (by [Eugene Chernyshov](https://github.com/Evgenus))
* [BigInteger](https://github.com/peterolson/BigInteger.js) (by [Ingo Bürk](https://github.com/Airblader))
* [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds))
@@ -124,6 +125,7 @@ All definitions files include a header with the author and editors, so at some p
* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee))
* [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn))
* [http-string-parser](https://github.com/apiaryio/http-string-parser) (by [MIZUNE Pine](https://github.com/pine613))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz))
@@ -193,6 +195,7 @@ All definitions files include a header with the author and editors, so at some p
* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds))
* [js-url](https://github.com/websanova/js-url) (by [MIZUNE Pine](https://github.com/pine613))
* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/))
* [jsbn](http://www-cs-students.stanford.edu/%7Etjw/jsbn/) (by [Eugene Chernyshov](https://github.com/Evgenus))
* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz))
* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk))
* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/))
@@ -247,7 +250,9 @@ All definitions files include a header with the author and editors, so at some p
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [mysql](https://github.com/felixge/node-mysql) (by [William Johnston](https://github.com/wjohnsto))
* [nconf](https://github.com/flatiron/nconf) (by [Jeff Goddard](https://github.com/jedigo))
* [needle](https://github.com/tomas/needle) (by [San Chen](https://github.com/bigsan))
* [noble](https://github.com/sandeepmistry/noble) (by [Seon-Wook Park](https://github.com/swook))
* [nock](https://github.com/pgte/nock) (by [bonnici](https://github.com/bonnici))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
@@ -306,6 +311,7 @@ All definitions files include a header with the author and editors, so at some p
* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov))
* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [sjcl](http://crypto.stanford.edu/sjcl/) (by [Eugene Chernyshov](https://github.com/Evgenus))
* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin))
* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
+3 -2
View File
@@ -33,13 +33,14 @@ declare module ng.translate {
}
interface ITranslateService {
(key: string, ...params: string[]): ng.IPromise<string>;
(translationId: string, interpolateParams?: any, interpolationId?: string): ng.IPromise<string>;
(translationId: string[], interpolateParams?: any, interpolationId?: string): ng.IPromise<{ [key: string]: string }>;
cloakClassName(): string;
cloakClassName(name: string): ITranslateProvider;
fallbackLanguage(langKey?: string): string;
fallbackLanguage(langKey?: string[]): string;
instant(translationId: string, interpolateParams?: any, interpolationId?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string): string;
instant(translationId: string[], interpolateParams?: any, interpolationId?: string): { [key: string]: string };
isPostCompilingEnabled(): boolean;
preferredLanguage(): string;
proposedLanguage(): string;
+81
View File
@@ -0,0 +1,81 @@
/// <reference path="./bigint.d.ts" />
var bi: BigInt.BigInt;
var num: number;
var str: string;
var b: boolean;
BigInt.setRandom(() => { return 0; });
bi = BigInt.add(bi, bi);
bi = BigInt.addInt(bi, num);
str = BigInt.bigInt2str(bi, num);
str = BigInt.bigInt2str(bi, str);
num = BigInt.bitSize(bi);
bi = BigInt.dup(bi);
b = BigInt.equals(bi, bi);
b = BigInt.equalsInt(bi, num);
bi = BigInt.expand(bi, num);
var nums: number[] = BigInt.findPrimes(num);
bi = BigInt.GCD(bi, bi);
b = BigInt.greater(bi, bi);
b = BigInt.greaterShift(bi, bi, num);
bi = BigInt.int2bigInt(0);
bi = BigInt.int2bigInt(0, 0);
bi = BigInt.int2bigInt(0, 0, 0);
bi = BigInt.inverseMod(bi, bi);
bi = BigInt.inverseModInt(num, num);
b = BigInt.isZero(bi);
b = BigInt.millerRabin(bi, bi);
b = BigInt.millerRabinInt(num, num);
bi = BigInt.mod(bi, bi);
num = BigInt.modInt(bi, num);
bi = BigInt.mult(bi, bi);
bi = BigInt.multMod(bi, bi, bi);
b = BigInt.negative(bi);
bi = BigInt.powMod(bi, bi, bi);
bi = BigInt.randBigInt(num, num);
bi = BigInt.randTruePrime(num);
bi = BigInt.randProbPrime(num);
bi = BigInt.str2bigInt(str, num);
bi = BigInt.str2bigInt(str, num, 0);
bi = BigInt.str2bigInt(str, num, 0, 0);
bi = BigInt.str2bigInt(str, str);
bi = BigInt.str2bigInt(str, str, 0);
bi = BigInt.str2bigInt(str, str, 0, 0);
bi = BigInt.sub(bi, bi);
bi = BigInt.trim(bi, num);
BigInt.addInt_(bi, num);
BigInt.add_(bi, bi);
BigInt.copy_(bi, bi);
num = BigInt.copyInt_(bi, num);
BigInt.GCD_(bi, bi);
b = BigInt.inverseMod_(bi, bi);
BigInt.mod_(bi, bi);
BigInt.mult_(bi, bi);
BigInt.multMod_(bi, bi, bi);
BigInt.powMod_(bi, bi, bi);
BigInt.randBigInt_(bi, num, num);
BigInt.randTruePrime_(bi, num);
BigInt.sub_(bi, bi);
BigInt.addShift_(bi, bi, num);
BigInt.carry_(bi);
BigInt.divide_(bi, bi, bi, bi);
num = BigInt.divInt_(bi, num);
BigInt.eGCD_(bi, bi, bi, bi, bi);
BigInt.halve_(bi);
BigInt.leftShift_(bi, num);
BigInt.linComb_(bi, bi, num, num);
BigInt.linCombShift_(bi, bi, num, num);
BigInt.mont_(bi, bi, bi, num);
BigInt.multInt_(bi, num);
BigInt.rightShift_(bi, num);
BigInt.squareMod_(bi, bi);
BigInt.subShift_(bi, bi, num);
function someRandomRealCode() {
bi = BigInt.int2bigInt(22, 5);
bi = BigInt.str2bigInt("FFFFFFFFFFFFFFFFC90FDAA2", 16);
str = BigInt.bigInt2str(bi, 16);
}
+245
View File
@@ -0,0 +1,245 @@
// Type definitions for BigInt v5.5.1
// Project: https://github.com/Evgenus/BigInt
// Definitions by: Eugene Chernyshov <https://github.com/Evgenus>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module BigInt {
export interface BigInt extends Array<number> {
}
export interface IRandom {
(): number;
}
export function setRandom(random: IRandom): void;
// bigInt add(x,y)
// return (x+y) for bigInts x and y.
export function add(x: BigInt, y: BigInt): BigInt;
// bigInt addInt(x,n)
// return (x+n) where x is a bigInt and n is an integer.
export function addInt(x: BigInt, n: number): BigInt;
// string bigInt2str(x,base)
// return a string form of bigInt x in a given base, with 2 <= base <= 95
export function bigInt2str(x: BigInt, base: number): string;
export function bigInt2str(x: BigInt, base: string): string;
// int bitSize(x)
// return how many bits long the bigInt x is, not counting leading zeros
export function bitSize(x: BigInt): number;
// bigInt dup(x)
// return a copy of bigInt x
export function dup(x: BigInt): BigInt;
// boolean equals(x,y)
// is the bigInt x equal to the bigint y?
export function equals(x: BigInt, y: BigInt): boolean;
// boolean equalsInt(x,y)
// is bigint x equal to integer y?
export function equalsInt(x: BigInt, y: number): boolean;
// bigInt expand(x,n)
// return a copy of x with at least n elements, adding leading zeros if needed
export function expand(value: BigInt, n: number): BigInt;
// Array findPrimes(n)
// return array of all primes less than integer n
export function findPrimes(n: number): number[];
// bigInt GCD(x,y)
// return greatest common divisor of bigInts x and y (each with same number of elements).
export function GCD(x: BigInt, y: BigInt): BigInt;
// boolean greater(x,y)
// is x>y? (x and y are nonnegative bigInts)
export function greater(x: BigInt, y: BigInt): boolean;
// boolean greaterShift(x,y,shift)
// is (x <<(shift*bpe)) > y?
export function greaterShift(x: BigInt, y: BigInt, shift: number): boolean;
// bigInt int2bigInt(t,n,m)
// return a bigInt equal to integer t, with at least n bits and m array elements
export function int2bigInt(t: number, n?: number, m?: number): BigInt;
// bigInt inverseMod(x,n)
// return (x**(-1) mod n) for bigInts x and n. If no inverse exists, it returns null
export function inverseMod(x: BigInt, n: BigInt): BigInt;
// int inverseModInt(x,n)
// return x**(-1) mod n, for integers x and n. Return 0 if there is no inverse
export function inverseModInt(x: number, n: number): BigInt;
// boolean isZero(x)
// is the bigInt x equal to zero?
export function isZero(x: BigInt): boolean;
// boolean millerRabin(x,b)
// does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is bigInt, 1<b<x)
export function millerRabin(x: BigInt, b: BigInt): boolean;
// boolean millerRabinInt(x,b)
// does one round of Miller-Rabin base integer b say that bigInt x is possibly prime? (b is int, 1<b<x)
export function millerRabinInt(x: number, b: number): boolean;
// bigInt mod(x,n)
// return a new bigInt equal to (x mod n) for bigInts x and n.
export function mod(x: BigInt, n: BigInt): BigInt;
// int modInt(x,n)
// return x mod n for bigInt x and integer n.
export function modInt(x: BigInt, n: number): number;
// bigInt mult(x,y)
// return x*y for bigInts x and y. This is faster when y<x.
export function mult(x: BigInt, y: BigInt): BigInt;
// bigInt multMod(x,y,n)
// return (x*y mod n) for bigInts x,y,n. For greater speed, let y<x.
export function multMod(x: BigInt, y: BigInt, n: BigInt): BigInt;
// boolean negative(x)
// is bigInt x negative?
export function negative(x: BigInt): boolean;
// bigInt powMod(x,y,n)
// return (x**y mod n) where x,y,n are bigInts and ** is exponentiation. 0**0=1. Faster for odd n.
export function powMod(x: BigInt, y: BigInt, n: BigInt): BigInt;
// bigInt randBigInt(n,s)
// return an n-bit random BigInt (n>=1). If s=1, then the most significant of those n bits is set to 1.
export function randBigInt(n: number, s: number): BigInt;
// bigInt randTruePrime(k)
// return a new, random, k-bit, true prime bigInt using Maurer's algorithm.
export function randTruePrime(k: number): BigInt;
// bigInt randProbPrime(k)
// return a new, random, k-bit, probable prime bigInt (probability it's composite less than 2^-80).
export function randProbPrime(k: number): BigInt;
// bigInt str2bigInt(s,b,n,m)
// return a bigInt for number represented in string s in base b with at least n bits and m array elements
export function str2bigInt(s: string, b: number, n?: number, m?: number): BigInt;
export function str2bigInt(s: string, b: string, n?: number, m?: number): BigInt;
// bigInt sub(x,y)
// return (x-y) for bigInts x and y. Negative answers will be 2s complement
export function sub(x: BigInt, y: BigInt): BigInt;
// bigInt trim(x,k)
// return a copy of x with exactly k leading zero elements
export function trim(x: BigInt, k: number): BigInt;
// void addInt_(x,n)
// do x=x+n where x is a bigInt and n is an integer
export function addInt_(x: BigInt, n: number): void;
// void add_(x,y)
// do x=x+y for bigInts x and y
export function add_(x: BigInt, y: BigInt): void;
// void copy_(x,y)
// do x=y on bigInts x and y
export function copy_(x: BigInt, y: BigInt): void;
// void copyInt_(x,n)
// do x=n on bigInt x and integer n
export function copyInt_(x: BigInt, n: number): number;
// void GCD_(x,y)
// set x to the greatest common divisor of bigInts x and y, (y is destroyed). (This never overflows its array).
export function GCD_(x: BigInt, y: BigInt): void;
// boolean inverseMod_(x,n)
// do x=x**(-1) mod n, for bigInts x and n. Returns 1 (0) if inverse does (doesn't) exist
export function inverseMod_(x: BigInt, n: BigInt): boolean;
// void mod_(x,n)
// do x=x mod n for bigInts x and n. (This never overflows its array).
export function mod_(x: BigInt, n: BigInt): void;
// void mult_(x,y)
// do x=x*y for bigInts x and y.
export function mult_(x: BigInt, y: BigInt): void;
// void multMod_(x,y,n)
// do x=x*y mod n for bigInts x,y,n.
export function multMod_(x: BigInt, y: BigInt, n: BigInt): void;
// void powMod_(x,y,n)
// do x=x**y mod n, where x,y,n are bigInts (n is odd) and ** is exponentiation. 0**0=1.
export function powMod_(x: BigInt, y: BigInt, n: BigInt): void;
// void randBigInt_(b,n,s)
// do b = an n-bit random BigInt. if s=1, then nth bit (most significant bit) is set to 1. n>=1.
export function randBigInt_(b: BigInt, n: number, s: number): void;
// void randTruePrime_(ans,k)
// do ans = a random k-bit true random prime (not just probable prime) with 1 in the msb.
export function randTruePrime_(ans: BigInt, k: number): void;
// void sub_(x,y)
// do x=x-y for bigInts x and y. Negative answers will be 2s complement.
export function sub_(x: BigInt, y: BigInt): void;
// void addShift_(x,y,ys)
// do x=x+(y<<(ys*bpe))
export function addShift_(x: BigInt, y: BigInt, ys: number): void;
// void carry_(x)
// do carries and borrows so each element of the bigInt x fits in bpe bits.
export function carry_(x: BigInt): void;
// void divide_(x,y,q,r)
// divide x by y giving quotient q and remainder r
export function divide_(x: BigInt, y: BigInt, q: BigInt, r: BigInt): void;
// int divInt_(x,n)
// do x=floor(x/n) for bigInt x and integer n, and return the remainder. (This never overflows its array).
export function divInt_(x: BigInt, n: number): number;
// void eGCD_(x,y,d,a,b)
// sets a,b,d to positive bigInts such that d = GCD_(x,y) = a*x-b*y
export function eGCD_(x: BigInt, y: BigInt, d: BigInt, a: BigInt, b: BigInt): void;
// void halve_(x)
// do x=floor(|x|/2)*sgn(x) for bigInt x in 2's complement. (This never overflows its array).
export function halve_(x: BigInt): void;
// void leftShift_(x,n)
// left shift bigInt x by n bits. n<bpe.
export function leftShift_(x: BigInt, n: number): void;
// void linComb_(x,y,a,b)
// do x=a*x+b*y for bigInts x and y and integers a and b
export function linComb_(x: BigInt, y: BigInt, a: number, b: number): void;
// void linCombShift_(x,y,b,ys)
// do x=x+b*(y<<(ys*bpe)) for bigInts x and y, and integers b and ys
export function linCombShift_(x: BigInt, y: BigInt, b: number, ys: number): void;
// void mont_(x,y,n,np)
// Montgomery multiplication (see comments where the function is defined)
export function mont_(x: BigInt, y: BigInt, n: BigInt, np: number): void;
// void multInt_(x,n)
// do x=x*n where x is a bigInt and n is an integer.
export function multInt_(x: BigInt, n: number): void;
// void rightShift_(x,n)
// right shift bigInt x by n bits. 0 <= n < bpe. (This never overflows its array).
export function rightShift_(x: BigInt, n: number): void;
// void squareMod_(x,n)
// do x=x*x mod n for bigInts x,n
export function squareMod_(x: BigInt, n: BigInt): void;
// void subShift_(x,y,ys)
// do x=x-(y<<(ys*bpe)). Negative answers will be 2s complement.
export function subShift_(x: BigInt, y: BigInt, ys: number): void;
}
Vendored
+33 -5
View File
@@ -243,7 +243,7 @@ declare module D3 {
*
* @param map Array of objects to get the values from
*/
values(map: any[]): any[];
values(map: any): any[];
/**
* List the key-value entries of an associative array.
*
@@ -1159,6 +1159,19 @@ declare module D3 {
*/
(size: Array<number>): TreeLayout;
};
/**
* Gets or sets the available node size
*/
nodeSize: {
/**
* Gets the available node size
*/
(): Array<number>;
/**
* Sets the available node size
*/
(size: Array<number>): TreeLayout;
};
}
export interface PieLayout {
@@ -1720,10 +1733,21 @@ declare module D3 {
(): any[];
(values: any[]): Axis;
};
tickSubdivide(count: number): Axis;
tickSize(major?: number, minor?: number, end?: number): Axis;
tickSize: {
(): number;
(inner: number, outer?: number): Axis;
}
innerTickSize: {
(): number;
(value: number): Axis;
}
outerTickSize: {
(): number;
(value: number): Axis;
}
tickFormat(formatter: (value: any) => string): Axis;
nice(count?: number): Axis;
}
export interface Arc {
@@ -2569,7 +2593,10 @@ declare module D3 {
*
* @param clamp Enable or disable
*/
clamp(clamp: boolean): QuantitativeScale;
clamp: {
(): boolean;
(clamp: boolean): QuantitativeScale;
}
/**
* extend the scale domain to nice round numbers.
*
@@ -2587,7 +2614,7 @@ declare module D3 {
*
* @param count Aproximate representative values to return
*/
tickFormat(count: number): (n: number) => string;
tickFormat(count: number, format?: string): (n: number) => string;
/**
* create a new scale from an existing scale..
*/
@@ -2768,6 +2795,7 @@ declare module D3 {
};
tickFormat(count: number): (n: number) => string;
copy(): TimeScale;
nice(count?: number): TimeScale;
}
}
+43
View File
@@ -73,3 +73,46 @@ exports = (grunt: IGrunt) => {
fileMaps[0].src.length;
fileMaps[0].dest;
};
// Official grunt task template from
// https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js
exports.exports = function(grunt: IGrunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('taskName', 'task description', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
punctuation: '.',
separator: ', '
});
// Iterate over all specified file groups.
this.files.forEach(function(f: grunt.file.IFilesConfig) {
// Concat specified files.
var src = f.src.filter(function(filepath: string) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
return grunt.file.read(filepath);
}).join(grunt.util.normalizelf(options.separator));
// Handle options.
src += options.punctuation;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File "' + f.dest + '" created.');
});
});
};
+5
View File
@@ -690,6 +690,11 @@ declare module grunt {
* Log a list of obj properties (good for debugging flags).
*/
writeflags(obj: any): T
/**
* Log an warning with grunt.log.warn
*/
warn(msg: string): T
}
/**
@@ -0,0 +1,42 @@
/// <reference path="http-string-parser.d.ts" />
import parser = require("http-string-parser");
function test_request(): void {
var result = parser.parseRequest("HTTP/1.1 GET /\r\nHost: www.example.com\r\n\r\n");
var body: string = result.body;
var headers: { [key: string]: string } = result.headers;
var method: string = result.method;
var uri: string = result.uri;
}
function test_response(): void {
var response = parser.parseResponse("HTTP/1.1 200 OK\r\n\r\n");
var body: string = response.body;
var headers: { [key: string]: string } = response.headers;
var statusCode: string = response.statusCode;
var statusMessage: string = response.statusMessage;
}
function test_requestLine(): void {
var result = parser.parseRequestLine("HTTP/1.1 GET /");
var method: string = result.method;
var protocol: string = result.protocol;
var uri: string = result.uri;
}
function test_statusLine(): void {
var result = parser.parseStatusLine("HTTP/1.1 200 OK");
var protocol: string = result.protocol;
var statusCode: string = result.statusCode;
var statusMessage: string = result.statusMessage;
}
function test_headers(): void {
var result: { [key: string]: string } =
parser.parseHeaders("Content-Type: text/html; charset=utf-8\r\nContent-Length: 256\r\n");
}
+38
View File
@@ -0,0 +1,38 @@
// Type definitions for http-string-parser
// Project: https://github.com/apiaryio/http-string-parser
// Definitions by: MIZUNE Pine <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "http-string-parser" {
interface ParseRequestResult {
method: string;
uri: string;
headers: { [key: string]: string };
body: string;
}
interface ParseResponseResult {
statusCode: string;
statusMessage: string;
headers: { [key: string]: string };
body: string;
}
interface ParseRequestLineResult {
method: string;
uri: string;
protocol: string;
}
interface ParseStatusLineResult {
protocol: string;
statusCode: string;
statusMessage: string;
}
export function parseRequest(requestString: string): ParseRequestResult;
export function parseResponse(responseString: string): ParseResponseResult;
export function parseRequestLine(requestLineString: string): ParseRequestLineResult;
export function parseStatusLine(statusLine: string): ParseStatusLineResult;
export function parseHeaders(headerLines: string): { [key: string]: string };
}
+93
View File
@@ -0,0 +1,93 @@
/// <reference path="jsbn.d.ts" />
var BigInteger = jsbn.BigInteger;
// constructor tests
var x = new BigInteger("AABB", 16);
x = new BigInteger("75643564363473453456342378564387956906736546456235345");
// method tests
var isBigInteger: jsbn.BigInteger;
var isNumber: number;
var isBoolean: boolean;
var isString: string;
var isDivmod: jsbn.BigInteger[];
var isByteArray: number[];
x.copyTo(x);
x.fromInt(0);
x.fromString("CAFEBABE", 16);
x.clamp();
isString = x.toString();
isString = x.toString(16);
isBigInteger = x.negate();
isBigInteger = x.abs();
isNumber = x.compareTo(x);
isNumber = x.bitLength();
x.dlShiftTo(0, isBigInteger);
x.drShiftTo(0, isBigInteger);
x.lShiftTo(0, isBigInteger);
x.rShiftTo(0, isBigInteger);
x.subTo(x, isBigInteger);
x.multiplyTo(x, isBigInteger);
x.squareTo(isBigInteger);
x.divRemTo(x, isBigInteger, isBigInteger);
isBigInteger = x.mod(x);
isNumber = x.invDigit();
isBoolean = x.isEven();
isBigInteger = x.exp(0, {
convert: (x) => x,
revert: (x) => x,
reduce: (x) => x,
mulTo: (x) => x,
sqrTo: (x) => x
});
isBigInteger = x.modPowInt(0, x);
isBigInteger = x.clone();
isNumber = x.intValue();
isNumber = x.byteValue();
isNumber = x.shortValue();
isNumber = x.chunkSize(0);
isNumber = x.signum();
isString = x.toRadix(10);
x.fromRadix("123", 10);
x.fromNumber(1);
x.fromNumber(1, 2);
x.fromNumber(1, 2, 3);
isByteArray = x.toByteArray();
isBoolean = x.equals(x);
isBigInteger = x.min(x);
isBigInteger = x.max(x);
x.bitwiseTo(x, (x, y) => x + y, isBigInteger);
isBigInteger = x.and(x);
isBigInteger = x.or(x);
isBigInteger = x.xor(x);
isBigInteger = x.andNot(x);
isBigInteger = x.not();
isBigInteger = x.shiftLeft(0);
isBigInteger = x.shiftRight(0);
isNumber = x.getLowestSetBit();
isNumber = x.bitCount();
isBoolean = x.testBit(0);
isBigInteger = x.changeBit(0, (x, y) => x * y);
isBigInteger = x.setBit(0);
isBigInteger = x.clearBit(0);
isBigInteger = x.flipBit(0);
x.addTo(x, isBigInteger);
isBigInteger = x.add(x);
isBigInteger = x.subtract(x);
isBigInteger = x.multiply(x);
isBigInteger = x.square();
isBigInteger = x.divide(x);
isBigInteger = x.remainder(x);
isDivmod = x.divideAndRemainder(x);
x.dMultiply(0);
x.dAddOffset(0, 0);
isBigInteger = x.pow(0);
x.multiplyLowerTo(x, 0, isBigInteger);
x.multiplyUpperTo(x, 0, isBigInteger);
isBigInteger = x.modPow(x, x);
isBigInteger = x.gcd(x);
isNumber = x.modInt(0);
isBigInteger = x.modInverse(x);
isBoolean = x.isProbablePrime(0);
isBoolean = x.millerRabin(0);
+250
View File
@@ -0,0 +1,250 @@
// Type definitions for jsbn v1.2
// Project: http://www-cs-students.stanford.edu/%7Etjw/jsbn/
// Definitions by: Eugene Chernyshov <https://github.com/Evgenus>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module jsbn {
interface RandomGenerator {
nextBytes(bytes: number[]): void;
}
export class BigInteger {
constructor(a: number, c: RandomGenerator);
constructor(a: number, b: number, c: RandomGenerator);
constructor(a: string, b?: number);
constructor(a: number[], b?: number);
constructor(a: BigInteger);
s: number;
t: number;
data: number[]; // forge specific
DB: number;
DM: number;
DV: number;
FV: number;
F1: number;
F2: number;
// am: Compute w_j += (x*this_i), propagate carries,
am(i: number, x: number, w: BigInteger, j: number, c: number, n: number): number;
// (protected) copy this to r
copyTo(r: BigInteger): void;
// (protected) set from integer value x, -DV <= x < DV
fromInt(x: number): void;
// (protected) set from string and radix
fromString(x: string, b: number): void;
// (protected) clamp off excess high words
clamp(): void;
// (public) return string representation in given radix
toString(b?: number): string;
// (public) -this
negate(): BigInteger;
// (public) |this|
abs(): BigInteger;
// (public) return + if this > a, - if this < a, 0 if equal
compareTo(a: BigInteger): number;
// (public) return the number of bits in "this"
bitLength(): number;
// (protected) r = this << n*DB
dlShiftTo(n: number, r: BigInteger): void;
// (protected) r = this >> n*DB
drShiftTo(n: number, r: BigInteger): void;
// (protected) r = this << n
lShiftTo(n: number, r: BigInteger): void;
// (protected) r = this >> n
rShiftTo(n: number, r: BigInteger): void;
// (protected) r = this - a
subTo(a: BigInteger, r: BigInteger): void;
// (protected) r = this * a, r != this,a (HAC 14.12)
multiplyTo(a: BigInteger, r: BigInteger): void;
// (protected) r = this^2, r != this (HAC 14.16)
squareTo(r: BigInteger): void;
// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m. q or r may be null.
divRemTo(m: BigInteger, q: BigInteger, r: BigInteger): void;
// (public) this mod a
mod(a: BigInteger): BigInteger;
// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
invDigit(): number;
// (protected) true iff this is even
isEven(): boolean;
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
exp(e: number, z: Reduction): BigInteger;
// (public) this^e % m, 0 <= e < 2^32
modPowInt(e: number, m: BigInteger): BigInteger;
// (public)
clone(): BigInteger;
// (public) return value as integer
intValue(): number;
// (public) return value as byte
byteValue(): number;
// (public) return value as short (assumes DB>=16)
shortValue(): number;
// (protected) return x s.t. r^x < DV
chunkSize(r: number): number;
// (public) 0 if this == 0, 1 if this > 0
signum(): number;
// (protected) convert to radix string
toRadix(b: number): string;
// (protected) convert from radix string
fromRadix(s: string, b: number): void;
// (protected) alternate constructor
fromNumber(a: number, b?: number, c?: number): void;
// (public) convert to bigendian byte array
toByteArray(): number[];
equals(a: BigInteger): boolean;
min(a: BigInteger): BigInteger;
max(a: BigInteger): BigInteger;
// (protected) r = this op a (bitwise)
bitwiseTo(a: BigInteger, op: (x: number, y: number) => number, r: BigInteger): void;
// (public) this & a
and(a: BigInteger): BigInteger;
// (public) this | a
or(a: BigInteger): BigInteger;
// (public) this ^ a
xor(a: BigInteger): BigInteger;
// (public) this & ~a
andNot(a: BigInteger): BigInteger;
// (public) ~this
not(): BigInteger;
// (public) this << n
shiftLeft(n: number): BigInteger;
// (public) this >> n
shiftRight(n: number): BigInteger;
// (public) returns index of lowest 1-bit (or -1 if none)
getLowestSetBit(): number;
// (public) return number of set bits
bitCount(): number;
// (public) true iff nth bit is set
testBit(n: number): boolean;
// (protected) this op (1<<n)
changeBit(n: number, op: (x: number, y: number) => number): BigInteger;
// (protected) this op (1<<n)
setBit(n: number): BigInteger;
// (public) this & ~(1<<n)
clearBit(n: number): BigInteger
// (public) this ^ (1<<n)
flipBit(n: number): BigInteger
// (protected) r = this + a
addTo(a: BigInteger, r: BigInteger): void;
// (public) this + a
add(a: BigInteger): BigInteger;
// (public) this - a
subtract(a: BigInteger): BigInteger;
// (public) this * a
multiply(a: BigInteger): BigInteger;
// (public) this^2
square(): BigInteger;
// (public) this / a
divide(a: BigInteger): BigInteger;
// (public) this % a
remainder(a: BigInteger): BigInteger;
// (public) [this/a,this%a]
divideAndRemainder(a: BigInteger): BigInteger[]; // Array of 2 items
// (protected) this *= n, this >= 0, 1 < n < DV
dMultiply(n: number): void;
// (protected) this += n << w words, this >= 0
dAddOffset(n: number, w: number): void;
// (public) this^e
pow(e: number): BigInteger;
// (protected) r = lower n words of "this * a", a.t <= n
multiplyLowerTo(a: BigInteger, n: number, r: BigInteger): void;
// (protected) r = "this * a" without lower n words, n > 0
multiplyUpperTo(a: BigInteger, n: number, r: BigInteger): void;
// (public) this^e % m (HAC 14.85)
modPow(e: BigInteger, m: BigInteger): BigInteger;
// (public) gcd(this,a) (HAC 14.54)
gcd(a: BigInteger): BigInteger;
// (protected) this % n, n < 2^26
modInt(n: number): number;
// (public) 1/this % m (HAC 14.61)
modInverse(m: BigInteger): BigInteger;
// (public) test primality with certainty >= 1-.5^t
isProbablePrime(t: number): boolean;
// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
millerRabin(t: number): boolean;
static ZERO: BigInteger;
static ONE: BigInteger;
}
interface Reduction {
convert(x: BigInteger): BigInteger;
revert(x: BigInteger): BigInteger;
reduce(x: BigInteger): void;
mulTo(x: BigInteger, y: BigInteger, r: BigInteger): void;
sqrTo(x: BigInteger, r: BigInteger): void;
}
}
+301
View File
@@ -0,0 +1,301 @@
/// <reference path="leaflet.d.ts" />
// initialize the map on the "map" div with a given center and zoom
var div = document.getElementById('map');
var map : L.Map = L.map(div, {
center: L.latLng([51.505, -0.09]),
zoom: 13,
minZoom: 3,
maxZoom: 8,
maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]),
dragging: true,
touchZoom: true,
scrollWheelZoom: true,
boxZoom: true,
tap: true,
tapTolerance: 30,
trackResize: true,
worldCopyJump: false,
closePopupOnClick: true,
bounceAtZoomLimits: true,
keyboard: true,
keyboardPanOffset: 80,
keyboardZoomOffset: 1,
inertia: true,
inertiaDeceleration: 3000,
inertiaMaxSpeed: 1500,
inertiaThreshold: 32,
zoomControl: true,
attributionControl: true,
fadeAnimation: true,
zoomAnimation: true,
zoomAnimationThreshold: 4,
markerZoomAnimation: true
});
map.dragging.enable();
map.touchZoom.enable();
map.scrollWheelZoom.enable();
map.doubleClickZoom.enable();
map.boxZoom.enable();
map.tap.enable();
map.setView(new L.LatLng(42, 51));
map.setView(L.latLng(42, 51));
map.setView(L.latLng(42, 51), 12);
map.setView(L.latLng(42, 51), 12, {
reset: true,
pan: {
animate: true,
duration: 0.25,
easeLinearity: 0.25,
noMoveStart: false
},
zoom: {
animate: true
}
});
map.setZoom(50);
map.setZoom(50, {});
map.zoomIn();
map.zoomOut();
map.zoomIn(2);
map.zoomOut(2);
map.zoomIn(2, { animate: true });
map.zoomOut(2, { animate: true });
map.setZoomAround(L.latLng(42, 51), 8, { animate: false });
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), {
paddingTopLeft: L.point(20, 20),
paddingBottomRight: L.point(20, 20),
padding: L.point(0, 0),
maxZoom: null
});
map.fitWorld();
map.fitWorld({
animate: false
});
map.panTo(L.latLng(42, 42));
map.panTo(L.latLng(42, 42), {
animate: true
});
map.invalidateSize(true);
map.invalidateSize({ reset: true });
map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)));
map.locate();
map.locate({
watch: false,
setView: false,
maxZoom: 18,
timeout: 10000,
maximumAge: 0,
enableHighAccuracy: false
});
map.stopLocate();
map.remove();
var center : L.LatLng = map.getCenter();
var zoom : number = map.getZoom();
var minZoom: number = map.getMinZoom();
var maxZoom: number = map.getMaxZoom();
var bounds: L.LatLngBounds = map.getBounds();
var boundsZoom: number = map.getBoundsZoom(bounds, true);
var size: L.Point = map.getSize();
var pixelBounds: L.Bounds = map.getPixelBounds();
var pixelOrigin: L.Point = map.getPixelOrigin();
var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png");
map.addLayer(layer);
map.addLayer(layer, false);
map.removeLayer(layer);
map.hasLayer(layer);
map.openPopup("canard", L.latLng(42, 51));
var popup = L.popup({
autoPan: true
});
map.openPopup(popup);
map.closePopup(popup);
map.closePopup();
map.addControl(L.control.attribution({position: 'bottomright'}));
map.removeControl(L.control.attribution({ position: 'bottomright' }));
map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0)));
map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0)));
map.containerPointToLayerPoint(L.point(0, 0));
map.layerPointToContainerPoint(L.point(0, 0));
map.project(map.unproject(L.point(10, 20)));
map.project(map.unproject(L.point(10, 20), 12), 12);
var mouseEvent: L.LeafletMouseEvent;
map.mouseEventToContainerPoint(mouseEvent);
map.mouseEventToLayerPoint(mouseEvent);
map.mouseEventToLatLng(mouseEvent);
map.getContainer().classList.add('roger');
map.getPanes().mapPane.classList.add('roger');
map.getPanes().markerPane.classList.add('roger');
map.getPanes().objectsPane.classList.add('roger');
map.getPanes().overlayPane.classList.add('roger');
map.getPanes().popupPane.classList.add('roger');
map.getPanes().shadowPane.classList.add('roger');
map.getPanes().tilePane.classList.add('roger');
map.whenReady((m: L.Map) => {
m.zoomOut();
});
map.on('click', () => {
map.zoomOut();
});
map.off('dblclick', L.Util.falseFn);
map.once('contextmenu', (e: L.LeafletMouseEvent) => {
map.openPopup('contextmenu', e.latlng);
});
var marker = L.marker(L.latLng(42, 51), {
icon: L.icon({
iconURl: 'roger.png',
iconRetinaUrl: 'roger-retina.png',
iconSize: L.point(40, 40),
iconAnchor: L.point(20, 0),
shadowUrl: 'roger-shadow.png',
shadowRetinaUrl: 'roger-shadow-retina.png',
shadowSize: L.point(44, 44),
shadowAnchor: L.point(22, 0),
popupAnchor: L.point(0, 0),
className: 'roger-icon'
}),
clickable: true,
draggable: false,
keyboard: true,
title: 'this is an icon',
alt: '',
zIndexOffset: 0,
opacity: 1.0,
riseOnHover: false,
riseOffset: 250
});
marker.addTo(map);
marker.on('click', (e: L.LeafletMouseEvent) => {
map.setView(e.latlng);
});
marker.once('mouseover', () => {
marker.openPopup();
})
marker.setLatLng(marker.getLatLng());
marker.setIcon(L.icon({}));
marker.setZIndexOffset(30);
marker.setOpacity(0.8);
marker.bindPopup(popup);
marker.unbindPopup();
marker.bindPopup('hello', {
closeOnClick: true
});
marker.openPopup();
marker.closePopup();
marker.togglePopup();
marker.togglePopup();
marker.setPopupContent('hello 3')
marker.getPopup().setContent('hello 2');
marker.update();
marker.toGeoJSON();
marker.dragging.enable();
popup = L.popup({
maxWidth: 300,
minWidth: 50,
maxHeight: null,
autoPan: true,
keepInView: false,
closeButton: true,
offset: L.point(0, 6),
autoPanPaddingTopLeft: null,
autoPanPaddingBottomRight: L.point(20, 20),
autoPanPadding: L.point(5, 5),
zoomAnimation: true,
closeOnClick: null,
className: 'roger'
});
popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map);
popup.update();
var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', {
foo: 'bar',
minZoom: 0,
maxZoom: 18,
maxNativeZoom: 17,
tileSize: 256,
subdomains: ['a','b','c'],
errorTileUrl: '',
attribution: '',
tms: false,
continuousWorld: false,
noWrap: false,
zoomOffset: 0,
zoomReverse: false,
opacity: 1.0,
zIndex: null,
unloadInvisibleTiles: false,
updateWhenIdle: false,
detectRetina: true,
reuseTiles: true,
bounds: null
});
tileLayer.on('loading', L.Util.falseFn)
.off('loading', L.Util.falseFn)
.once('tileload', L.Util.falseFn);
tileLayer.addTo(map);
tileLayer.bringToBack()
.bringToFront()
.setOpacity(0.7)
.setZIndex(9)
.redraw()
.setUrl('http://perdu.com')
.getContainer();
+161 -8
View File
@@ -1,4 +1,4 @@
// Type definitions for Leaflet.js 0.6.4
// Type definitions for Leaflet.js 0.7.3
// Project: https://github.com/Leaflet/Leaflet
// Definitions by: Vladimir Zotov <https://github.com/rgripper>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -870,6 +870,13 @@ declare module L {
* Default value: [0, 0].
*/
padding?: Point;
/**
* The maximum possible zoom to use.
*
* Default value: null
*/
maxZoom?: number;
}
}
@@ -1128,6 +1135,11 @@ declare module L {
* Mercator-based CRS.
*/
scale(zoom: number): number;
/**
* Returns the size of the world in pixels for a particular zoom.
*/
getSize(zoom: number): Point;
}
}
@@ -1231,6 +1243,10 @@ declare module L {
*/
enabled(): boolean;
}
export class Handler extends Class {
initialize(map: Map): void;
}
}
declare module L {
@@ -1251,6 +1267,15 @@ declare module L {
onRemove(map: Map): void;
}
}
declare module L {
export module Mixin {
export interface LeafletMixinEvents extends IEventPowered<LeafletMixinEvents> {
}
export var Events: LeafletMixinEvents;
}
}
declare module L {
@@ -1277,6 +1302,11 @@ declare module L {
* Sets the opacity of the overlay.
*/
setOpacity(opacity: number): ImageOverlay;
/**
* Changes the URL of the image.
*/
setUrl(imageUrl: string): ImageOverlay;
/**
* Brings the layer to the top of all overlays.
@@ -1802,6 +1832,17 @@ declare module L {
popup: Popup;
}
}
declare module L {
export interface LeafletDragEndEvent extends LeafletEvent {
/**
* The distance in pixels the draggable element was moved by.
*/
distance: number;
}
}
declare module L {
@@ -1960,7 +2001,7 @@ declare module L {
* Sets the view of the map (geographical center and zoom) with the given
* animation options.
*/
setView(center: LatLng, zoom: number, options?: ZoomPanOptions): Map;
setView(center: LatLng, zoom?: number, options?: ZoomPanOptions): Map;
/**
* Sets the zoom of the map.
@@ -2142,7 +2183,7 @@ declare module L {
/**
* Closes the popup previously opened with openPopup (or the given one).
*/
closePopup(): Map;
closePopup(popup?: Popup): Map;
/**
* Adds the given control to the map.
@@ -2370,17 +2411,26 @@ declare module L {
/**
* Whether the map can be zoomed by using the mouse wheel.
* If passed 'center', it will zoom to the center of the view regardless of
* where the mouse was.
*
* Default value: true.
*/
scrollWheelZoom?: boolean;
scrollWheelZoom?: any;
//scrollWheelZoom?: boolean;
//scrollWheelZoom?: string;
/**
* Whether the map can be zoomed in by double clicking on it.
* Whether the map can be zoomed in by double clicking on it and zoomed out
* by double clicking while holding shift.
* If passed 'center', double-click zoom will zoom to the center of the view
* regardless of where the mouse was.
*
* Default value: true.
*/
doubleClickZoom?: boolean;
doubleClickZoom?: string;
//doubleClickZoom?: boolean;
//doubleClickZoom?: string;
/**
* Whether the map can be zoomed to a rectangular area specified by dragging
@@ -2529,6 +2579,14 @@ declare module L {
* in all browsers that support CSS3 Transitions except Android.
*/
markerZoomAnimation?: boolean;
/**
* Set it to false if you don't want the map to zoom beyond min/max zoom
* and then bounce back when pinch-zooming.
*
* Default value: true.
*/
bounceAtZoomLimits?: boolean;
}
}
@@ -2652,6 +2710,11 @@ declare module L {
* Opens the popup previously bound by the bindPopup method.
*/
openPopup(): Marker;
/**
* Returns the popup previously bound by the bindPopup method.
*/
getPopup(): Popup;
/**
* Closes the bound popup of the marker if it's opened.
@@ -2676,7 +2739,12 @@ declare module L {
/**
* Returns a GeoJSON representation of the marker (GeoJSON Point Feature).
*/
toGeoJSON(popup: Popup, options?: PopupOptions): any;
toGeoJSON(): any;
/**
* Marker dragging handler (by both mouse and touch).
*/
dragging: IHandler;
////////////
////////////
@@ -2752,6 +2820,13 @@ declare module L {
* Default value: ''.
*/
title?: string;
/**
* Text for the alt attribute of the icon image (useful for accessibility).
*
* Default value: ''.
*/
alt?: string;
/**
* By default, marker images zIndex is set automatically based on its latitude.
@@ -2814,6 +2889,11 @@ declare module L {
*/
getLatLngs(): LatLng[][];
/**
* Opens the popup previously bound by bindPopup.
*/
openPopup(): MultiPolygon;
/**
* Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature).
*/
@@ -2848,6 +2928,11 @@ declare module L {
*/
getLatLngs(): LatLng[][];
/**
* Opens the popup previously bound by bindPopup.
*/
openPopup(): MultiPolyline;
/**
* Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature).
*/
@@ -3076,6 +3161,20 @@ declare module L {
* layers (e.g. Android 2).
*/
dashArray?: string;
/**
* A string that defines shape to be used at the end of the stroke.
*
* Default: null.
*/
lineCap?: string;
/**
* A string that defines shape to be used at the corners of the stroke.
*
* Default: null.
*/
lineJoin?: string;
/**
* If false, the vector will not emit mouse events and will act as a part of the
@@ -3089,6 +3188,13 @@ declare module L {
* Sets the pointer-events attribute on the path if SVG backend is used.
*/
pointerEvents?: boolean;
/**
* Custom class name set on an element.
*
* Default value: ''.
*/
className?: string;
}
}
@@ -3308,7 +3414,12 @@ declare module L {
* Sets the geographical point where the popup will open.
*/
setLatLng(latlng: LatLng): Popup;
/**
* Returns the geographical point of popup.
*/
getLatLng(): LatLng;
/**
* Sets the HTML content of the popup.
*/
@@ -3319,6 +3430,12 @@ declare module L {
*/
setContent(el: HTMLElement): Popup;
/**
* Returns the content of the popup.
*/
getContent(): HTMLElement;
//getContent(): string;
////////////
////////////
/**
@@ -3333,6 +3450,12 @@ declare module L {
* the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer).
*/
onRemove(map: Map): void;
/**
* Updates the popup content, layout and position. Useful for updating the popup after
* something inside changed, e.g. image loaded.
*/
update(): Popup;
}
}
@@ -3382,6 +3505,22 @@ declare module L {
* Default value: new Point(0, 6).
*/
offset?: Point;
/**
* The margin between the popup and the top left corner of the map view after
* autopanning was performed.
*
* Default value: null.
*/
autoPanPaddingTopLeft?: Point;
/**
* The margin between the popup and the bottom right corner of the map view after
* autopanning was performed.
*
* Default value: null.
*/
autoPanPaddingBottomRight?: Point;
/**
* The margin between the popup and the edges of the map view after autopanning
@@ -3695,6 +3834,15 @@ declare module L {
* Default value: 18.
*/
maxZoom?: number;
/**
* Maximum zoom number the tiles source has available. If it is specified,
* the tiles on all zoom levels higher than maxNativeZoom will be loaded from
* maxZoom level and auto-scaled.
*
* Default value: null.
*/
maxNativeZoom?: number;
/**
* Tile size (width and height in pixels, assuming tiles are square).
@@ -3997,6 +4145,11 @@ declare module L {
* An equivalent of passing animate to both zoom and pan options (see below).
*/
animate?: boolean;
/**
* If true, it will delay moveend event so that it doesn't happen many times in a row.
*/
debounceMoveend?: boolean;
}
}
+6 -6
View File
@@ -1,6 +1,6 @@
// Type definitions for Moment.js 2.5.0
// Project: https://github.com/timrwood/moment
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface MomentInput {
@@ -203,9 +203,9 @@ interface Moment {
isSame(b: Date, granularity: string): boolean;
isSame(b: number[], granularity: string): boolean;
lang(language: string): void;
lang(reset: boolean): void;
lang(): string;
lang(language: string): Moment;
lang(reset: boolean): Moment;
lang(): MomentLanguage;
max(date: Date): Moment;
max(date: number): Moment;
@@ -313,8 +313,8 @@ interface MomentStatic {
isMoment(): boolean;
isMoment(m: any): boolean;
lang(language: string): any;
lang(language: string, definition: MomentLanguage): any;
lang(language?: string): string;
lang(language?: string, definition?: MomentLanguage): string;
longDateFormat: any;
relativeTime: any;
meridiem: (hour: number, minute: number, isLowercase: boolean) => string;
+381
View File
@@ -0,0 +1,381 @@
/// <reference path="mysql.d.ts" />
import mysql = require('mysql');
/// Connections
var connection = mysql.createConnection({
host: 'localhost',
user: 'me',
password: 'secret'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
connection = mysql.createConnection({
host: 'example.org',
user: 'bob',
password: 'secret'
});
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
connection.query('SELECT 1', function (err, rows) {
// connected! (unless `err` is set)
});
connection = mysql.createConnection({
host: 'localhost',
ssl: {
ca: ''
}
});
connection = mysql.createConnection({
host: 'localhost',
ssl: {
// DO NOT DO THIS
// set up your ca correctly to trust the connection
rejectUnauthorized: false
}
});
connection.end(function (err) {
// The connection is terminated now
});
connection.destroy();
connection.changeUser({ user: 'john' }, function (err) {
if (err) throw err;
});
var userId = 'some user provided value';
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function (err, results) {
// ...
});
connection.query('SELECT * FROM users WHERE id = ?', [userId], function (err, results) {
// ...
});
var post = { id: 1, title: 'Hello MySQL' };
var query = connection.query('INSERT INTO posts SET ?', post, function (err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
var queryStr = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");
console.log(queryStr); // SELECT * FROM posts WHERE title='Hello MySQL'
var sorter = 'date';
var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);
connection.query(sql, function (err, results) {
// ...
});
var sorter = 'date';
var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter);
connection.query(sql, function (err, results) {
// ...
});
var userIdNum = 1;
var columns = ['username', 'email'];
var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userIdNum], function (err, results) {
// ...
});
console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1
var sql = "SELECT * FROM ?? WHERE ?? = ?";
var inserts = ['users', 'id', userId];
sql = mysql.format(sql, inserts);
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt: string, key: string) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
connection.query('INSERT INTO posts SET ?', { title: 'test' }, function (err, result) {
if (err) throw err;
console.log(result.insertId);
});
connection.query('DELETE FROM posts WHERE title = "wrong"', function (err, result) {
if (err) throw err;
console.log('deleted ' + result.affectedRows + ' rows');
});
connection.query('UPDATE posts SET ...', function (err, result) {
if (err) throw err;
console.log('changed ' + result.changedRows + ' rows');
});
connection.connect(function (err) {
if (err) throw err;
console.log('connected as id ' + connection.threadId);
});
/// Pools
var poolConfig = {
connectionLimit: 10,
host: 'example.org',
user: 'bob',
password: 'secret'
};
var pool = mysql.createPool(poolConfig);
pool.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
pool = mysql.createPool({
host: 'example.org',
user: 'bob',
password: 'secret'
});
pool.getConnection(function (err, connection) {
// connected! (unless `err` is set)
});
pool.on('connection', function (connection) {
connection.query('SET SESSION auto_increment_increment=1')
});
pool.getConnection(function (err, connection) {
// Use the connection
connection.query('SELECT something FROM sometable', function (err, rows) {
// And done with the connection.
connection.release();
// Don't use the connection here, it has been returned to the pool.
});
});
/// PoolClusters
// create
var poolCluster = mysql.createPoolCluster();
poolCluster.add(poolConfig); // anonymous group
poolCluster.add('MASTER', poolConfig);
poolCluster.add('SLAVE1', poolConfig);
poolCluster.add('SLAVE2', poolConfig);
// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
poolCluster.getConnection(function (err, connection) { });
// Target Group : MASTER, Selector : round-robin
poolCluster.getConnection('MASTER', function (err, connection) { });
// Target Group : SLAVE1-2, Selector : order
// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
poolCluster.on('remove', function (nodeId) {
console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1
});
poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) { });
// of namespace : of(pattern, selector)
poolCluster.of('*').getConnection(function (err, connection) { });
var pool = poolCluster.of('SLAVE*', 'RANDOM');
pool.getConnection(function (err, connection) { });
pool.getConnection(function (err, connection) { });
// destroy
poolCluster.end();
/// Queries
var query = connection.query('SELECT * FROM posts');
query
.on('error', function (err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function (fields) {
// the field packets for the rows to follow
})
.on('result', function (row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
var processRow = (row: any, cb: () => void) => {
cb();
};
processRow(row, function () {
connection.resume();
});
})
.on('end', function () {
// all rows have been received
});
connection.query('SELECT * FROM posts')
.stream({ highWaterMark: 5 })
.pipe(() => { });
connection = mysql.createConnection({ multipleStatements: true });
connection.query('SELECT 1; SELECT 2', function (err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
var query = connection.query('SELECT 1; SELECT 2');
query
.on('fields', function (fields, index) {
// the fields for the result rows that follow
})
.on('result', function (row, index) {
// index refers to the statement this result belongs to (starts at 0)
});
var options = { sql: '...', nestTables: true };
connection.query(options, function (err, results) {
/* results will be an array like this now:
[{
table1: {
fieldA: '...',
fieldB: '...',
},
table2: {
fieldA: '...',
fieldB: '...',
},
}, ...]
*/
});
connection.beginTransaction(function (err) {
var title = 'title';
if (err) { throw err; }
connection.query('INSERT INTO posts SET title=?', title, function (err, result) {
if (err) {
connection.rollback(function () {
throw err;
});
}
var log = 'Post ' + result.insertId + ' added';
connection.query('INSERT INTO log SET data=?', log, function (err, result) {
if (err) {
connection.rollback(function () {
throw err;
});
}
connection.commit(function (err) {
if (err) {
connection.rollback(function () {
throw err;
});
}
console.log('success!');
});
});
});
});
// Kill query after 60s
connection.query({ sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000 }, function (err, rows) {
if (err && err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {
throw new Error('too long to count table rows!');
}
if (err) {
throw err;
}
console.log(rows[0].count + ' rows');
});
connection = mysql.createConnection({
port: 84943, // WRONG PORT
});
connection.connect(function (err) {
console.log(err.code); // 'ECONNREFUSED'
console.log(err.fatal); // true
});
connection.query('SELECT 1', function (err) {
console.log(err.code); // 'ECONNREFUSED'
console.log(err.fatal); // true
});
connection.query('USE name_of_db_that_does_not_exist', function (err, rows) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
connection.query('SELECT 1', function (err, rows) {
console.log(err); // null
console.log(rows.length); // 1
});
connection.on('error', function (err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
connection.query('USE name_of_db_that_does_not_exist');
// I am Chuck Norris:
connection.on('error', function () { });
connection = mysql.createConnection({ typeCast: false });
var query = connection.query({ sql: '...', typeCast: false }, function (err, results) {
});
connection.query({
sql: '...',
typeCast: function (field: any, next: Function) {
if (field.type == 'TINY' && field.length == 1) {
return (field.string() == '1'); // 1 = true, 0 = false
}
return next();
}
});
connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS");
connection = mysql.createConnection({ debug: true });
connection = mysql.createConnection({ debug: ['ComQueryPacket', 'RowDataPacket'] });
+487
View File
@@ -0,0 +1,487 @@
// Type definitions for node-mysql
// Project: https://github.com/felixge/node-mysql
// Definitions by: William Johnston <https://github.com/wjohnsto>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module mysql {
export interface IMySql {
createConnection(connectionUri: string): IConnection;
createConnection(config: IConnectionConfig): IConnection;
createPool(config: IPoolConfig): IPool;
createPoolCluster(config?: IPoolClusterConfig): IPoolCluster;
escape(value: any): string;
format(sql: string): string;
format(sql: string, values: Array<any>): string;
}
export interface IConnectionStatic {
createQuery(sql: string): IQuery;
createQuery(sql: string, callback: (err: IError, ...args: any[]) => void): IQuery;
createQuery(sql: string, values: Array<any>): IQuery;
createQuery(sql: string, values: Array<any>, callback: (err: IError, ...args: any[]) => void): IQuery;
}
export interface IConnection {
config: IConnectionConfig;
threadId: number;
beginTransaction(callback: (err: IError) => void): void;
connect(): void;
connect(callback: (err: IError, ...args: any[]) => void): void;
connect(options: any, callback?: (err: IError, ...args: any[]) => void): void;
commit(callback: (err: IError) => void): void;
changeUser(options: IConnectionOptions): void;
changeUser(options: IConnectionOptions, callback: (err: IError) => void): void;
query: IQueryFunction;
end(): void;
end(callback: (err: IError, ...args: any[]) => void): void;
end(options: any, callback: (err: IError, ...args: any[]) => void): void;
destroy(): void;
pause(): void;
release(): void;
resume(): void;
escape(value: any): string;
escapeId(value: string): string;
escapeId(values: Array<string>): string;
format(sql: string): string;
format(sql: string, values: Array<any>): string;
on(ev: string, callback: (...args: any[]) => void): IConnection;
on(ev: 'error', callback: (err: IError) => void): IConnection;
rollback(callback: () => void): void;
}
export interface IPool {
config: IPoolConfig;
getConnection(callback: (err: IError, connection: IConnection) => void): void;
query: IQueryFunction;
on(ev: string, callback: (...args: any[]) => void): IPool;
on(ev: 'connection', callback: (connection: IConnection) => void): IPool;
on(ev: 'error', callback: (err: IError) => void): IPool;
}
export interface IPoolCluster {
config: IPoolClusterConfig;
add(config: IPoolConfig): void;
add(group: string, config: IPoolConfig): void;
end(): void;
getConnection(callback: (err: IError, connection: IConnection) => void): void;
getConnection(group: string, callback: (err: IError, connection: IConnection) => void): void;
getConnection(group: string, selector: string, callback: (err: IError, connection: IConnection) => void): void;
of(pattern: string): IPool;
of(pattern: string, selector: string): IPool;
on(ev: string, callback: (...args: any[]) => void): IPoolCluster;
on(ev: 'remove', callback: (nodeId: number) => void): IPoolCluster;
on(ev: 'connection', callback: (connection: IConnection) => void): IPoolCluster;
on(ev: 'error', callback: (err: IError) => void): IPoolCluster;
}
export interface IQuery {
/**
* The SQL for a constructed query
*/
sql: string;
/**
* Emits a query packet to start the query
*/
start(): void;
/**
* Determines the packet class to use given the first byte of the packet.
*
* @param firstByte The first byte of the packet
* @param parser The packet parser
*/
determinePacket(firstByte: number, parser: any): any;
/**
* Creates a Readable stream with the given options
*
* @param options The options for the stream.
*/
stream(options: IStreamOptions): IQuery;
/**
* Pipes a stream downstream, providing automatic pause/resume based on the
* options sent to the stream.
*
* @param options The options for the stream.
*/
pipe(callback: (...args: any[]) => void): IQuery;
on(ev: string, callback: (...args: any[]) => void): IQuery;
on(ev: 'error', callback: (err: IError) => void): IQuery;
on(ev: 'fields', callback: (fields: any, index: number) => void): IQuery;
on(ev: 'result', callback: (row: any, index: number) => void): IQuery;
on(ev: 'end', callback: () => void): IQuery;
}
export interface IQueryFunction {
(sql: string): IQuery;
(sql: string, callback: (err: IError, ...args: any[]) => void): IQuery;
(sql: string, values: Array<any>): IQuery;
(sql: string, values: Array<any>, callback: (err: IError, ...args: any[]) => void): IQuery;
(sql: string, values: any): IQuery;
(sql: string, values: any, callback: (err: IError, ...args: any[]) => void): IQuery;
(options: IQueryOptions): IQuery;
(options: IQueryOptions, callback: (err: IError, ...args: any[]) => void): IQuery;
(options: IQueryOptions, values: Array<any>): IQuery;
(options: IQueryOptions, values: Array<any>, callback: (err: IError, ...args: any[]) => void): IQuery;
(options: IQueryOptions, values: any): IQuery;
(options: IQueryOptions, values: any, callback: (err: IError, ...args: any[]) => void): IQuery;
}
export interface IQueryOptions {
/**
* The SQL for the query
*/
sql: string;
/**
* Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for
* operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout
* operations through the client. This means that when a timeout is reached, the connection it occurred on will be
* destroyed and no further operations can be performed.
*/
timeout?: number;
/**
* Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be
* nested as tableName_fieldName
*/
nestTables?: any;
/**
* Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
* to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
*
* You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
*
* WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
*
* field.string()
* field.buffer()
* field.geometry()
*
* are aliases for
*
* parser.parseLengthCodedString()
* parser.parseLengthCodedBuffer()
* parser.parseGeometryValue()
*
* You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
*/
typeCast?: any;
}
export interface IStreamOptions {
/**
* Sets the max buffer size in objects of a stream
*/
highWaterMark?: number;
/**
* The object mode of the stream (Default: true)
*/
objectMode?: any;
}
export interface IConnectionOptions {
/**
* The MySQL user to authenticate as
*/
user?: string;
/**
* The password of that MySQL user
*/
password?: string;
/**
* Name of the database to use for this connection
*/
database?: string;
/**
* The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci).
* If a SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used.
* (Default: 'UTF8_GENERAL_CI')
*/
charset?: string;
}
export interface IConnectionConfig extends IConnectionOptions {
/**
* The hostname of the database you are connecting to. (Default: localhost)
*/
host?: string;
/**
* The port number to connect to. (Default: 3306)
*/
port?: number;
/**
* The source IP address to use for TCP connection
*/
localAddress?: string;
/**
* The path to a unix domain socket to connect to. When used host and port are ignored
*/
socketPath?: string;
/**
* The timezone used to store local dates. (Default: 'local')
*/
timezone?: string;
/**
* The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default: 10 seconds)
*/
connectTimeout?: number;
/**
* Stringify objects instead of converting to values. (Default: 'false')
*/
stringifyObjects?: boolean;
/**
* Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default: false)
*/
insecureAuth?: boolean;
/**
* Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
* to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
*
* You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
*
* WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
*
* field.string()
* field.buffer()
* field.geometry()
*
* are aliases for
*
* parser.parseLengthCodedString()
* parser.parseLengthCodedBuffer()
* parser.parseGeometryValue()
*
* You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
*/
typeCast?: any;
/**
* A custom query format function
*/
queryFormat?: (query: string, values: any) => void;
/**
* When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option
* (Default: false)
*/
supportBigNumbers?: boolean;
/**
* Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be
* always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving
* bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately
* represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)
* (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects.
* This option is ignored if supportBigNumbers is disabled.
*/
bigNumberStrings?: boolean;
/**
* Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date
* objects. (Default: false)
*/
dateStrings?: boolean;
/**
* This will print all incoming and outgoing packets on stdout.
* You can also restrict debugging to packet types by passing an array of types (strings) to debug;
*
* (Default: false)
*/
debug?: any;
/**
* Generates stack traces on Error to include call site of library entrance ("long stack traces"). Slight
* performance penalty for most calls. (Default: true)
*/
trace?: boolean;
/**
* Allow multiple mysql statements per query. Be careful with this, it exposes you to SQL injection attacks. (Default: false)
*/
multipleStatements?: boolean;
/**
* List of connection flags to use other than the default ones. It is also possible to blacklist default ones
*/
flags?: Array<string>;
/**
* object with ssl parameters or a string containing name of ssl profile
*/
ssl?: any;
}
export interface IPoolConfig extends IConnectionConfig {
/**
* The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout,
* because acquiring a pool connection does not always involve making a connection. (Default: 10 seconds)
*/
acquireTimeout?: number;
/**
* Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue
* the connection request and call it when one becomes available. If false, the pool will immediately call back with an error.
* (Default: true)
*/
waitForConnections?: boolean;
/**
* The maximum number of connections to create at once. (Default: 10)
*/
connectionLimit?: number;
/**
* The maximum number of connection requests the pool will queue before returning an error from getConnection. If set to 0, there
* is no limit to the number of queued connection requests. (Default: 0)
*/
queueLimit?: number;
}
export interface IPoolClusterConfig {
/**
* If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)
*/
canRetry?: boolean;
/**
* If connection fails, node's errorCount increases. When errorCount is greater than removeNodeErrorCount,
* remove a node in the PoolCluster. (Default: 5)
*/
removeNodeErrorCount?: number;
/**
* The default selector. (Default: RR)
* RR: Select one alternately. (Round-Robin)
* RANDOM: Select the node by random function.
* ORDER: Select the first node available unconditionally.
*/
defaultSelector?: string;
}
export interface ISslCredentials {
/**
* A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
*/
pfx?: string;
/**
* A string holding the PEM encoded private key
*/
key?: string;
/**
* A string of passphrase for the private key or pfx
*/
passphrase?: string;
/**
* A string holding the PEM encoded certificate
*/
cert?: string;
/**
* Either a string or list of strings of PEM encoded CA certificates to trust.
*/
ca?: Array<string>;
/**
* Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
*/
crl?: Array<string>;
/**
* A string describing the ciphers to use or exclude
*/
ciphers?: string;
}
export interface IError extends Error {
/**
* Either a MySQL server error (e.g. 'ER_ACCESS_DENIED_ERROR'),
* a node.js error (e.g. 'ECONNREFUSED') or an internal error
* (e.g. 'PROTOCOL_CONNECTION_LOST').
*/
code: string;
/**
* The error number for the error code
*/
errno: number;
/**
* The sql state marker
*/
sqlStateMarker?: string;
/**
* The sql state
*/
sqlState?: string;
/**
* The field count
*/
fieldCount?: number;
/**
* The stack trace for the error
*/
stack?: string;
/**
* Boolean, indicating if this error is terminal to the connection object.
*/
fatal: boolean;
}
}
declare module 'mysql' {
var mysql: mysql.IMySql;
export = mysql;
}
+108
View File
@@ -0,0 +1,108 @@
/// <reference path="needle.d.ts" />
import needle = require("needle");
function Usage() {
// using callback
needle.get('http://ifconfig.me/all.json', function (error, response) {
if (!error)
console.log(response.body.ip_addr); // JSON decoding magic. :)
});
// using streams
var out: any; // = fs.createWriteStream('logo.png');
needle.get('https://google.com/images/logo.png').pipe(out);
}
function ResponsePipeline() {
needle.get('http://stackoverflow.com/feeds', { compressed: true }, function (err, resp) {
console.log(resp.body); // this little guy won't be a Gzipped binary blob
// but a nice object containing all the latest entries
});
var options = {
compressed: true,
follow: true,
rejectUnauthorized: true
};
// in this case, we'll ask Needle to follow redirects (disabled by default),
// but also to verify their SSL certificates when connecting.
var stream = needle.get('https://backend.server.com/everything.html', options);
stream.on('readable', function () {
var data: any;
while (data = this.read()) {
console.log(data.toString());
}
});
}
function API_head() {
var options = {
timeout: 5000 // if we don't get a response in 5 seconds, boom.
};
needle.head('https://my.backend.server.com', function (err, resp) {
if (err) {
console.log('Shoot! Something is wrong: ' + err.message);
}
else {
console.log('Yup, still alive.');
}
});
}
function API_get() {
needle.get('google.com/search?q=syd+barrett', function (err, resp) {
// if no http:// is found, Needle will automagically prepend it.
});
}
function API_post() {
var options = {
headers: { 'X-Custom-Header': 'Bumbaway atuna' }
};
needle.post('https://my.app.com/endpoint', 'foo=bar', options, function (err, resp) {
// you can pass params as a string or as an object.
});
}
function API_put() {
var nested = {
params: {
are: {
also: 'supported'
}
}
};
needle.put('https://api.app.com/v2', nested, function (err, resp) {
console.log('Got ' + resp.bytes + ' bytes.') // another nice treat from this handsome fella.
});
}
function API_delete() {
var options = {
username: 'fidelio',
password: 'x'
};
needle.delete('https://api.app.com/messages/123', null, options, function (err, resp) {
// in this case, data may be null, but you need to explicity pass it.
});
}
function API_request() {
var data = {
q: 'a very smart query',
page: 2,
format: 'json'
};
needle.request('get', 'forum.com/search', data, function (err, resp) {
if (!err && resp.statusCode == 200)
console.log(resp.body); // here you go, mister.
});
}
+88
View File
@@ -0,0 +1,88 @@
// Type definitions for needle 0.7.8
// Project: https://github.com/tomas/needle
// Definitions by: San Chen <https://github.com/bigsan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module Needle {
interface ReadableStream extends NodeJS.ReadableStream {
}
interface Callback {
(error: Error, response: any, body: any): void;
}
interface RequestOptions {
timeout?: number;
follow?: any; // number | string
multipart?: boolean;
proxy?: string;
agent?: string;
headers?: any;
auth?: string; // auto | digest | basic (default)
json?: boolean;
}
interface ResponseOptions {
decode?: boolean;
parse?: boolean;
output?: any;
}
interface HttpHeaderOptions {
compressed?: boolean;
username?: string;
password?: string;
accept?: string;
connection?: string;
user_agent?: string;
}
interface TLSOptions {
pfx?: any;
key?: any;
passphrase?: string;
cert?: any;
ca?: any;
ciphers?: any;
rejectUnauthorized?: boolean;
secureProtocol?: any;
}
interface NeedleOptions extends RequestOptions, ResponseOptions, HttpHeaderOptions, TLSOptions {
}
interface NeedleStatic {
defaults(options?: any): void;
head(url: string): ReadableStream;
head(url: string, callback?: Callback): ReadableStream;
head(url: string, options?: RequestOptions, callback?: Callback): ReadableStream;
get(url: string): ReadableStream;
get(url: string, callback?: Callback): ReadableStream;
get(url: string, options?: RequestOptions, callback?: Callback): ReadableStream;
post(url: string, data: any): ReadableStream;
post(url: string, data: any, callback?: Callback): ReadableStream;
post(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
put(url: string, data: any): ReadableStream;
put(url: string, data: any, callback?: Callback): ReadableStream;
put(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
delete(url: string, data: any): ReadableStream;
delete(url: string, data: any, callback?: Callback): ReadableStream;
delete(url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
request(method: string, url: string, data: any): ReadableStream;
request(method: string, url: string, data: any, callback?: Callback): ReadableStream;
request(method: string, url: string, data: any, options?: RequestOptions, callback?: Callback): ReadableStream;
}
}
declare module "needle" {
var needle: Needle.NeedleStatic;
export = needle;
}
+1 -1
View File
@@ -367,7 +367,7 @@ interface FileUploadResult {
interface Flags {
create: boolean;
exclusive: boolean;
exclusive?: boolean;
}
/*
Vendored
+1
View File
@@ -214,6 +214,7 @@ declare module Q {
export function nfapply<T>(nodeFunction: Function, args: any[]): Promise<T>;
export function ninvoke<T>(nodeModule: any, functionName: string, ...args: any[]): Promise<T>;
export function npost<T>(nodeModule: any, functionName: string, args: any[]): Promise<T>;
export function nsend<T>(nodeModule: any, functionName: string, ...args: any[]): Promise<T>;
export function nmcall<T>(nodeModule: any, functionName: string, ...args: any[]): Promise<T>;
+267
View File
@@ -0,0 +1,267 @@
/// <reference path="./sjcl.d.ts" />
var b: boolean;
var n: number;
var s: string;
var bn: sjcl.BigNumber;
var ba: sjcl.BitArray;
function testBigNumber() {
bn = new sjcl.bn();
bn = new sjcl.bn(0);
bn = new sjcl.bn("0");
bn = new sjcl.bn(bn);
bn = bn.initWith(0);
bn = bn.initWith("0");
bn = bn.initWith(bn);
bn = bn.addM(0);
bn = bn.addM("0");
bn = bn.addM(bn);
bn = bn.subM(0);
bn = bn.subM("0");
bn = bn.subM(bn);
bn = bn.mod(0);
bn = bn.mod("0");
bn = bn.mod(bn);
bn = bn.inverseMod(0);
bn = bn.inverseMod("0");
bn = bn.inverseMod(bn);
bn = bn.add(0);
bn = bn.add("0");
bn = bn.add(bn);
bn = bn.sub(0);
bn = bn.sub("0");
bn = bn.sub(bn);
bn = bn.mul(0);
bn = bn.mul("0");
bn = bn.mul(bn);
bn = bn.mulmod(0, 0);
bn = bn.mulmod(0, "0");
bn = bn.mulmod(0, bn);
bn = bn.mulmod("0", 0);
bn = bn.mulmod("0", "0");
bn = bn.mulmod("0", bn);
bn = bn.mulmod(bn, 0);
bn = bn.mulmod(bn, "0");
bn = bn.mulmod(bn, bn);
bn = bn.powermod(0, 0);
bn = bn.powermod(0, "0");
bn = bn.powermod(0, bn);
bn = bn.powermod("0", 0);
bn = bn.powermod("0", "0");
bn = bn.powermod("0", bn);
bn = bn.powermod(bn, 0);
bn = bn.powermod(bn, "0");
bn = bn.powermod(bn, bn);
bn = bn.copy();
b = bn.equals(0);
b = bn.equals(bn);
b = bn.greaterEquals(0);
b = bn.greaterEquals(bn);
n = bn.getLimb(0);
s = bn.toString();
bn = bn.doubleM();
bn = bn.halveM();
bn = bn.square();
bn = bn.power(1);
bn = bn.power([1, 1]);
bn = bn.power(bn);
bn = bn.trim();
bn = bn.reduce();
bn = bn.fullReduce();
bn = bn.normalize();
bn = bn.cnormalize();
ba = bn.toBits();
ba = bn.toBits(1);
n = bn.bitLength();
bn = sjcl.bn.fromBits(ba);
}
function testBitArray() {
ba = sjcl.bitArray.bitSlice(ba, 0, 1);
n = sjcl.bitArray.extract(ba, 0, 1);
ba = sjcl.bitArray.concat(ba, ba);
n = sjcl.bitArray.bitLength(ba);
ba = sjcl.bitArray.clamp(ba, 0);
n = sjcl.bitArray.partial(1, 1);
n = sjcl.bitArray.partial(1, 1, 0);
n = sjcl.bitArray.getPartial(0);
b = sjcl.bitArray.equal(ba, ba);
ba = sjcl.bitArray._shiftRight(ba, 0);
ba = sjcl.bitArray._shiftRight(ba, 0, 0);
ba = sjcl.bitArray._shiftRight(ba, 0, 0, ba);
}
function testCodecs() {
s = sjcl.codec.base64.fromBits(ba);
ba = sjcl.codec.base64.toBits(s);
s = sjcl.codec.base64url.fromBits(ba);
ba = sjcl.codec.base64url.toBits(s);
s = sjcl.codec.hex.fromBits(ba);
ba = sjcl.codec.hex.toBits(s);
s = sjcl.codec.utf8String.fromBits(ba);
ba = sjcl.codec.utf8String.toBits(s);
var bytes: number[] = sjcl.codec.bytes.fromBits(ba);
ba = sjcl.codec.bytes.toBits(bytes);
}
function testHashes() {
var hash: sjcl.SjclHash;
ba = hash.reset().update("xxx").update(ba).finalize();
hash = new sjcl.hash.sha1();
hash = new sjcl.hash.sha1(hash);
ba = sjcl.hash.sha1.hash(ba);
ba = sjcl.hash.sha1.hash("xxx");
hash = new sjcl.hash.sha256();
hash = new sjcl.hash.sha256(hash);
ba = sjcl.hash.sha256.hash(ba);
ba = sjcl.hash.sha256.hash("xxx");
hash = new sjcl.hash.sha512();
hash = new sjcl.hash.sha512(hash);
ba = sjcl.hash.sha512.hash(ba);
ba = sjcl.hash.sha512.hash("xxx");
}
function testSymetric() {
var aes = new sjcl.cipher.aes([0, 0, 0, 0]);
ba = sjcl.mode.cbc.encrypt(aes, ba, ba);
ba = sjcl.mode.cbc.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.gcm.encrypt(aes, ba, ba);
ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.gcm.encrypt(aes, ba, ba, ba, 128);
ba = sjcl.mode.ccm.encrypt(aes, ba, ba);
ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.ccm.encrypt(aes, ba, ba, ba, 128);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128);
ba = sjcl.mode.ocb2.encrypt(aes, ba, ba, ba, 128, false);
}
function testHmacPbdkf2() {
ba = sjcl.misc.pbkdf2("xxx", "xxx");
ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000);
ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12);
ba = sjcl.misc.pbkdf2("xxx", "xxx", 1000, 12, sjcl.misc.hmac);
ba = sjcl.misc.pbkdf2("xxx", ba);
ba = sjcl.misc.pbkdf2("xxx", ba, 1000);
ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12);
ba = sjcl.misc.pbkdf2("xxx", ba, 1000, 12, sjcl.misc.hmac);
ba = sjcl.misc.pbkdf2(ba, "xxx");
ba = sjcl.misc.pbkdf2(ba, "xxx", 1000);
ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12);
ba = sjcl.misc.pbkdf2(ba, "xxx", 1000, 12, sjcl.misc.hmac);
ba = sjcl.misc.pbkdf2(ba, ba);
ba = sjcl.misc.pbkdf2(ba, ba, 1000);
ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12);
ba = sjcl.misc.pbkdf2(ba, ba, 1000, 12, sjcl.misc.hmac);
var hmac: sjcl.SjclHmac;
hmac = new sjcl.misc.hmac(ba);
hmac = new sjcl.misc.hmac(ba, sjcl.hash.sha512);
ba = hmac.mac("xxx");
ba = hmac.mac(ba);
ba = hmac.encrypt("xxx");
ba = hmac.encrypt(ba);
hmac.reset();
hmac.update("xxx");
hmac.update(ba);
ba = hmac.digest();
}
function testECC() {
var keys = sjcl.ecc.elGamal.generateKeys(192, 0);
var ciphertext = sjcl.encrypt(keys.pub, "hello world");
var plaintext = sjcl.decrypt(keys.sec, ciphertext);
// TODO: Maybe deeper testing required. Let me know
}
function testRandom() {
b = sjcl.random.isReady();
ba = sjcl.random.randomWords(8);
ba = sjcl.random.randomWords(8, 6);
var rnd = new sjcl.prng(1);
ba = rnd.randomWords(16);
ba = rnd.randomWords(16, 6);
}
function testSRP() {
var group = sjcl.keyexchange.srp.knownGroup(1024);
ba = sjcl.codec.hex.toBits(s);
ba = sjcl.keyexchange.srp.makeX(s, s, ba);
ba = sjcl.keyexchange.srp.makeVerifier(s, s, ba, group);
}
function testConvenince() {
var x: sjcl.SjclCipherEncrypted;
x = sjcl.encrypt("xxx", "text");
s = sjcl.decrypt(ba, x);
x = sjcl.encrypt("xxx", "text", { iv: ba, salt: ba });
s = sjcl.decrypt(ba, x, { iv: ba, salt: ba });
var y: sjcl.SjclCipherDecrypted;
sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm" }, x);
s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm" }, y);
sjcl.encrypt("xxx", "text", { iv: ba, salt: ba, mode: "gcm", iter: 200 }, x);
s = sjcl.decrypt(ba, x, { iv: ba, salt: ba, mode: "gcm", iter: 200 }, y);
}
+556
View File
@@ -0,0 +1,556 @@
// Type definitions for sjcl v1.0.1
// Project: http://crypto.stanford.edu/sjcl/
// Definitions by: Eugene Chernyshov <https://github.com/Evgenus>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module sjcl {
export var bn: BigNumberStatic;
export var bitArray: BitArrayStatic;
export var codec: SjclCodecs;
export var hash: SjclHashes;
export var exception: SjclExceptions;
export var cipher: SjclCiphers;
export var mode: SjclModes;
export var misc: SjclMisc;
export var ecc: SjclEllipticCurveCryptography;
export var random: SjclRandom;
export var prng: SjclRandomStatic;
export var keyexchange: SjclKeyExchange;
export var json: SjclJson;
export var encrypt: SjclConveninceEncryptor;
export var decrypt: SjclConveninceDecryptor;
// ________________________________________________________________________
interface BigNumber {
radix: number;
maxMul: number;
copy(): BigNumber;
/// Initializes this with it, either as a bn, a number, or a hex string.
initWith: TypeHelpers.BigNumberBinaryOperator;
/// Returns true if "this" and "that" are equal. Calls fullReduce().
/// Equality test is in constant time.
equals(that: number): boolean;
equals(that: BigNumber): boolean;
/// Get the i'th limb of this, zero if i is too large.
getLimb(index: number): number;
/// Constant time comparison function.
/// Returns 1 if this >= that, or zero otherwise.
greaterEquals(that: number): boolean;
greaterEquals(that: BigNumber): boolean;
/// Convert to a hex string.
toString(): string;
/// this += that. Does not normalize.
addM: TypeHelpers.BigNumberBinaryOperator;
/// this *= 2. Requires normalized; ends up normalized.
doubleM(): BigNumber;
/// this /= 2, rounded down. Requires normalized; ends up normalized.
halveM(): BigNumber;
/// this -= that. Does not normalize.
subM: TypeHelpers.BigNumberBinaryOperator;
mod: TypeHelpers.BigNumberBinaryOperator;
/// return inverse mod prime p. p must be odd. Binary extended Euclidean algorithm mod p.
inverseMod: TypeHelpers.BigNumberBinaryOperator;
/// this + that. Does not normalize.
add: TypeHelpers.BigNumberBinaryOperator;
/// this - that. Does not normalize.
sub: TypeHelpers.BigNumberBinaryOperator;
/// this * that. Normalizes and reduces.
mul: TypeHelpers.BigNumberBinaryOperator;
/// this ^ 2. Normalizes and reduces.
square(): BigNumber;
/// this ^ n. Uses square-and-multiply. Normalizes and reduces.
power(n: number): BigNumber;
power(n: BigNumber): BigNumber;
power(a: number[]): BigNumber;
/// this * that mod N
mulmod: TypeHelpers.BigNumberTrinaryOperator;
/// this ^ x mod N
powermod: TypeHelpers.BigNumberTrinaryOperator;
trim(): BigNumber;
/// Reduce mod a modulus. Stubbed for subclassing.
reduce(): BigNumber;
/// Reduce and normalize.
fullReduce(): BigNumber;
/// Propagate carries.
normalize(): BigNumber;
/// Constant-time normalize. Does not allocate additional space.
cnormalize(): BigNumber;
/// Serialize to a bit array
toBits(len?: number): BitArray;
/// Return the length in bits, rounded up to the nearest byte.
bitLength(): number;
}
interface BigNumberStatic {
new (): BigNumber;
new (n: string): BigNumber;
new (n: number): BigNumber;
new (n: BigNumber): BigNumber;
fromBits(bits: BitArray): BigNumber;
random: TypeHelpers.Bind1<number>;
prime: {
p127: PseudoMersennePrimeStatic;
// Bernstein's prime for Curve25519
p25519: PseudoMersennePrimeStatic;
// Koblitz primes
p192k: PseudoMersennePrimeStatic;
p224k: PseudoMersennePrimeStatic;
p256k: PseudoMersennePrimeStatic;
// NIST primes
p192: PseudoMersennePrimeStatic;
p224: PseudoMersennePrimeStatic;
p256: PseudoMersennePrimeStatic;
p384: PseudoMersennePrimeStatic;
p521: PseudoMersennePrimeStatic;
};
pseudoMersennePrime(exponent: number, coeff: number[][]): PseudoMersennePrimeStatic;
}
interface PseudoMersennePrime extends BigNumber {
reduce(): PseudoMersennePrime;
fullReduce(): PseudoMersennePrime;
inverse(): PseudoMersennePrime;
}
interface PseudoMersennePrimeStatic extends BigNumberStatic {
new (): PseudoMersennePrime;
new (n: string): PseudoMersennePrime;
new (n: number): PseudoMersennePrime;
new (n: BigNumber): PseudoMersennePrime;
}
// ________________________________________________________________________
interface BitArray extends Array<number> {
}
interface BitArrayStatic {
/// Array slices in units of bits.
bitSlice(a: BitArray, bstart: number, bend: number): BitArray;
/// Extract a number packed into a bit array.
extract(a: BitArray, bstart: number, blenth: number): number;
/// Concatenate two bit arrays.
concat(a1: BitArray, a2: BitArray): BitArray
/// Find the length of an array of bits.
bitLength(a: BitArray): number;
/// Truncate an array.
clamp(a: BitArray, len: number): BitArray;
/// Make a partial word for a bit array.
partial(len: number, x: number, _end?: number): number;
/// Get the number of bits used by a partial word.
getPartial(x: number): number;
/// Compare two arrays for equality in a predictable amount of time.
equal(a: BitArray, b: BitArray): boolean;
/// Shift an array right.
_shiftRight(a: BitArray, shift: number, carry?: number, out?: BitArray): BitArray;
/// xor a block of 4 words together.
_xor4(x: number[], y: number[]): number[];
}
// ________________________________________________________________________
interface SjclCodec<T> {
fromBits(bits: BitArray): T;
toBits(value: T): BitArray;
}
interface SjclCodecs {
utf8String: SjclCodec<string>;
hex: SjclCodec<string>;
bytes: SjclCodec<number[]>;
base64: SjclCodec<string>;
base64url: SjclCodec<string>;
}
// ________________________________________________________________________
interface SjclHash {
reset(): SjclHash;
update(data: string): SjclHash;
update(data: BitArray): SjclHash;
finalize(): BitArray;
}
interface SjclHashStatic {
new (hash?: SjclHash): SjclHash;
hash(data: string): BitArray;
hash(data: BitArray): BitArray;
}
interface SjclHashes {
sha1: SjclHashStatic;
sha256: SjclHashStatic;
sha512: SjclHashStatic;
}
// ________________________________________________________________________
interface SjclExceptions {
corrupt: SjclExceptionFactory;
invalid: SjclExceptionFactory;
bug: SjclExceptionFactory;
notReady: SjclExceptionFactory;
}
interface SjclExceptionFactory {
new (message: string): Error;
}
// ________________________________________________________________________
interface SjclCiphers {
aes: SjclCipherStatic;
}
interface SjclCipher {
encrypt(data: number[]): number[];
decrypt(data: number[]): number[];
}
interface SjclCipherStatic {
new (key: number[]): SjclCipher;
}
// ________________________________________________________________________
interface SjclModes {
gcm: SjclGCMMode;
ccm: SjclCCMMode;
ocb2: SjclOCB2Mode;
cbc: SjclCBCMode;
}
interface SjclGCMMode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
}
interface SjclCCMMode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number): BitArray;
}
interface SjclOCB2Mode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray, tlen?: number, premac?: boolean): BitArray;
pmac(prp: SjclCipher, adata: BitArray): number[];
}
interface SjclCBCMode {
encrypt(prp: SjclCipher, plaintext: BitArray, iv: BitArray, adata?: BitArray): BitArray;
decrypt(prp: SjclCipher, ciphertext: BitArray, iv: BitArray, adata?: BitArray): BitArray;
}
// ________________________________________________________________________
interface Pbkdf2Params {
iter?: number;
salt?: BitArray;
}
interface SjclMisc {
pbkdf2(password: string, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
pbkdf2(password: BitArray, salt: string, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
pbkdf2(password: BitArray, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
pbkdf2(password: string, salt: BitArray, count?: number, length?: number, Prff?: SjclPseudorandomFunctionFamilyStatic): BitArray;
hmac: SjclHmacStatic;
cachedPbkdf2(password: string, obj?: Pbkdf2Params): {
key: BitArray;
salt: BitArray;
};
}
class SjclPseudorandomFunctionFamily {
encrypt(data: string): BitArray;
encrypt(data: BitArray): BitArray;
}
interface SjclHmac extends SjclPseudorandomFunctionFamily {
mac(data: string): BitArray;
mac(data: BitArray): BitArray;
reset(): void;
update(data: string): void;
update(data: BitArray): void;
digest(): BitArray;
}
interface SjclPseudorandomFunctionFamilyStatic {
new (key: BitArray): SjclPseudorandomFunctionFamily;
}
interface SjclHmacStatic {
new (key: BitArray, Hash?: SjclHashStatic): SjclHmac;
}
// ________________________________________________________________________
interface SjclEllipticCurveCryptography {
point: SjclEllipticalPointStatic;
pointJac: SjclPointJacobianStatic;
curve: SjclEllipticalCurveStatic;
curves: {
c192: SjclEllipticalCurve;
c224: SjclEllipticalCurve;
c256: SjclEllipticalCurve;
c384: SjclEllipticalCurve;
k192: SjclEllipticalCurve;
k224: SjclEllipticalCurve;
k256: SjclEllipticalCurve;
};
basicKey: SjclECCBasic;
elGamal: SjclElGamal;
ecdsa: SjclEcdsa;
}
interface SjclEllipticalPoint {
toJac(): SjclPointJacobian;
mult(k: BigNumber): SjclEllipticalPoint;
mult2(k: BigNumber, k2: BigNumber, affine2: SjclEllipticalPoint): SjclEllipticalPoint;
multiples(): Array<SjclEllipticalPoint>;
isValid(): boolean;
toBits(): BitArray;
}
interface SjclEllipticalPointStatic {
new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber): SjclEllipticalPoint;
}
interface SjclPointJacobian {
add(T: SjclEllipticalPoint): SjclPointJacobian;
doubl(): SjclPointJacobian;
toAffine(): SjclEllipticalPoint;
mult(k: BigNumber, affine: SjclEllipticalPoint): SjclPointJacobian;
mult2(k1: BigNumber, affine: SjclEllipticalPoint, k2: BigNumber, affine2: SjclEllipticalPoint): SjclPointJacobian;
isValid(): boolean;
}
interface SjclPointJacobianStatic {
new (curve: SjclEllipticalCurve, x?: BigNumber, y?: BigNumber, z?: BigNumber):SjclPointJacobian;
}
interface SjclEllipticalCurve {
fromBits(bits: BitArray): SjclEllipticalPoint;
}
interface SjclEllipticalCurveStatic {
new (Field: BigNumber, r: BigNumber, a: BigNumber, b: BigNumber, x: BigNumber, y: BigNumber): SjclEllipticalCurve;
}
interface SjclKeyPair<P extends SjclECCPublicKey, S extends SjclECCSecretKey> {
pub: P;
sec: S;
}
interface SjclKeysGenerator<P extends SjclECCPublicKey, S extends SjclECCSecretKey> {
(curve: SjclEllipticalCurve, paranoia: number, sec?: BigNumber): SjclKeyPair<P, S>;
(curve: number, paranoia: number, sec?: BigNumber): SjclKeyPair<P, S>;
}
interface SjclECCPublicKeyData {
x: BitArray;
y: BitArray;
}
class SjclECCPublicKey {
get(): SjclECCPublicKeyData;
}
class SjclECCSecretKey {
get(): BitArray;
}
interface SjclECCPublicKeyFactory<T extends SjclECCPublicKey> {
new (curve: SjclEllipticalCurve, point: SjclEllipticalPoint): T;
new (curve: SjclEllipticalCurve, point: BitArray): T;
}
interface SjclECCSecretKeyFactory<T extends SjclECCSecretKey> {
new (curve: SjclEllipticalCurve, exponent: BigNumber): T;
}
interface SjclECCBasic {
publicKey: SjclECCPublicKeyFactory<SjclECCPublicKey>;
secretKey: SjclECCSecretKeyFactory<SjclECCSecretKey>;
generateKeys(cn: string): SjclKeysGenerator<SjclECCPublicKey, SjclECCSecretKey>;
}
class SjclElGamalPublicKey extends SjclECCPublicKey {
kem(paranoia: number): {
key: BitArray;
tag: BitArray;
};
}
class SjclElGamalSecretKey extends SjclECCSecretKey {
unkem(tag: BitArray): BitArray;
dh(pk: SjclECCPublicKey): BitArray;
}
interface SjclElGamal {
publicKey: SjclECCPublicKeyFactory<SjclElGamalPublicKey>;
secretKey: SjclECCSecretKeyFactory<SjclElGamalSecretKey>;
generateKeys: SjclKeysGenerator<SjclElGamalPublicKey, SjclElGamalSecretKey>;
}
class SjclEcdsaPublicKey extends SjclECCPublicKey {
verify(hash: BitArray, rs: BitArray, fakeLegacyVersion: boolean): boolean;
}
class SjclEcdsaSecretKey extends SjclECCSecretKey {
sign(hash: BitArray, paranoia: number, fakeLegacyVersion: boolean, fixedKForTesting?: BigNumber): BitArray;
}
interface SjclEcdsa {
publicKey: SjclECCPublicKeyFactory<SjclEcdsaPublicKey>;
secretKey: SjclECCSecretKeyFactory<SjclEcdsaSecretKey>;
generateKeys: SjclKeysGenerator<SjclEcdsaPublicKey, SjclEcdsaSecretKey>;
}
// ________________________________________________________________________
interface SjclRandom {
randomWords(nwords: number, paranoia?: number): BitArray;
setDefaultParanoia(paranoia: number, allowZeroParanoia: string): void;
addEntropy(data: number, estimatedEntropy: number, source: string): void;
addEntropy(data: number[], estimatedEntropy: number, source: string): void;
addEntropy(data: string, estimatedEntropy: number, source: string): void;
isReady(paranoia?: number): boolean;
getProgress(paranoia?: number): number;
startCollectors(): void;
stopCollectors(): void;
addEventListener(name: string, cb: Function): void;
removeEventListener(name: string, cb: Function): void;
}
interface SjclRandomStatic {
new (defaultParanoia: number): SjclRandom;
}
// ________________________________________________________________________
interface SjclKeyExchange {
srp: SecureRemotePassword;
}
interface SjclSRPGroup {
N: BigNumber;
g: BigNumber;
}
interface SecureRemotePassword {
makeVerifier(username: string, password: string, salt: BitArray, group: SjclSRPGroup): BitArray;
makeX(username: string, password: string, salt: BitArray): BitArray;
knownGroup(i: string): SjclSRPGroup;
knownGroup(i: number): SjclSRPGroup;
}
// ________________________________________________________________________
interface SjclCipherParams {
v?: number;
iter?: number;
ks?: number;
ts?: number;
mode?: string;
adata?: string;
cipher?: string;
}
interface SjclCipherEncryptParams extends SjclCipherParams {
salt: BitArray;
iv: BitArray;
}
interface SjclCipherDecryptParams extends SjclCipherParams {
salt?: BitArray;
iv?: BitArray;
}
interface SjclCipherEncrypted extends SjclCipherEncryptParams {
kemtag?: BitArray;
ct: BitArray;
}
interface SjclCipherDecrypted extends SjclCipherEncrypted {
key: BitArray;
}
interface SjclConveninceEncryptor {
(password: string, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted;
(password: BitArray, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted;
(password: SjclElGamalPublicKey, plaintext: string, params?: SjclCipherEncryptParams, rp?: SjclCipherEncrypted): SjclCipherEncrypted;
}
interface SjclConveninceDecryptor {
(password: string, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string;
(password: BitArray, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string;
(password: SjclElGamalSecretKey, ciphertext: SjclCipherEncrypted, params?: SjclCipherDecryptParams, rp?: SjclCipherDecrypted): string;
}
interface SjclJson {
encrypt: SjclConveninceEncryptor;
decrypt: SjclConveninceDecryptor;
encode(obj: Object): string;
decode(obj: string): Object;
}
// ________________________________________________________________________
module TypeHelpers {
interface One<T> {
(value: T): BigNumber;
}
interface BigNumberBinaryOperator extends One<number>, One<string>, One<BigNumber> {
}
interface Two<T1, T2> {
(x: T1, N: T2): BigNumber;
}
interface Bind1<T> extends Two<number, T>, Two<string, T>, Two<BigNumber, T> {
}
interface BigNumberTrinaryOperator extends Bind1<number>, Bind1<string>, Bind1<BigNumber> {
}
}
}
+1 -1
View File
@@ -43,7 +43,7 @@
// Cube
var geometry = new THREE.CubeGeometry(200, 200, 200);
var geometry = new THREE.BoxGeometry(200, 200, 200);
for (var i = 0; i < geometry.faces.length; i += 2) {
@@ -1,5 +1,6 @@
/// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
/// <reference path="../../../tween.js/tween.js.d.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/canvas_interactive_cubes_tween.html
@@ -7,7 +7,6 @@
// ------- variable definitions that does not exist in the original code. These are for typescript.
// -------
var camera, scene, renderer,
particle1, particle2, particle3,
light1, light2, light3,
loader, mesh;
@@ -43,14 +42,14 @@
}
particle1 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xff0040, program: program }));
scene.add(particle1);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xff0040, program: program } ) );
light1.add( sprite );
particle2 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x0040ff, program: program }));
scene.add(particle2);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x0040ff, program: program } ) );
light2.add( sprite );
particle3 = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x80ff80, program: program }));
scene.add(particle3);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x80ff80, program: program } ) );
light3.add( sprite );
loader = new THREE.JSONLoader();
loader.load('obj/WaltHeadLo.js', function (geometry) {
@@ -94,29 +93,17 @@
if (mesh) mesh.rotation.y -= 0.01;
particle1.position.x = Math.sin(time * 0.7) * 30;
particle1.position.y = Math.cos(time * 0.5) * 40;
particle1.position.z = Math.cos(time * 0.3) * 30;
light1.position.x = Math.sin( time * 0.7 ) * 30;
light1.position.y = Math.cos( time * 0.5 ) * 40;
light1.position.z = Math.cos( time * 0.3 ) * 30;
light1.position.x = particle1.position.x;
light1.position.y = particle1.position.y;
light1.position.z = particle1.position.z;
light2.position.x = Math.cos( time * 0.3 ) * 30;
light2.position.y = Math.sin( time * 0.5 ) * 40;
light2.position.z = Math.sin( time * 0.7 ) * 30;
particle2.position.x = Math.cos(time * 0.3) * 30;
particle2.position.y = Math.sin(time * 0.5) * 40;
particle2.position.z = Math.sin(time * 0.7) * 30;
light2.position.x = particle2.position.x;
light2.position.y = particle2.position.y;
light2.position.z = particle2.position.z;
particle3.position.x = Math.sin(time * 0.7) * 30;
particle3.position.y = Math.cos(time * 0.3) * 40;
particle3.position.z = Math.sin(time * 0.5) * 30;
light3.position.x = particle3.position.x;
light3.position.y = particle3.position.y;
light3.position.z = particle3.position.z;
light3.position.x = Math.sin( time * 0.7 ) * 30;
light3.position.y = Math.cos( time * 0.3 ) * 40;
light3.position.z = Math.sin( time * 0.5 ) * 30;
renderer.render(scene, camera);
+8 -11
View File
@@ -11,7 +11,7 @@
var container, stats;
var camera, scene, renderer, objects;
var particleLight, pointLight;
var pointLight;
init();
animate();
@@ -103,10 +103,6 @@
}
particleLight = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xffffff, program: program }));
particleLight.scale.x = particleLight.scale.y = 8;
scene.add(particleLight);
// Lights
scene.add(new THREE.AmbientLight(Math.random() * 0x202020));
@@ -121,6 +117,10 @@
pointLight = new THREE.PointLight(0xffffff, 1);
scene.add(pointLight);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xffffff, program: program } ) );
sprite.scale.set( 8, 8, 8 );
pointLight.add( sprite );
renderer = new THREE.CanvasRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
@@ -198,13 +198,10 @@
}
particleLight.position.x = Math.sin(timer * 7) * 300;
particleLight.position.y = Math.cos(timer * 5) * 400;
particleLight.position.z = Math.cos(timer * 3) * 300;
pointLight.position.x = Math.sin( timer * 7 ) * 300;
pointLight.position.y = Math.cos( timer * 5 ) * 400;
pointLight.position.z = Math.cos( timer * 3 ) * 300;
pointLight.position.x = particleLight.position.x;
pointLight.position.y = particleLight.position.y;
pointLight.position.z = particleLight.position.z;
renderer.render(scene, camera);
+7 -13
View File
@@ -1,5 +1,6 @@
/// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
/// <reference path="../../../tween.js/tween.js.d.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/css3d_sprites.html
@@ -26,23 +27,16 @@
scene = new THREE.Scene();
var sprite = document.createElement('img');
sprite.addEventListener('load', function (event) {
var image = document.createElement( 'img' );
image.addEventListener( 'load', function ( event ) {
for (var i = 0, j = 0; i < particlesTotal; i++, j += 3) {
for ( var i = 0; i < particlesTotal; i ++ ) {
var canvas = document.createElement('canvas');
canvas.width = sprite.width;
canvas.height = sprite.height;
var context = canvas.getContext('2d');
context.drawImage(sprite, 0, 0);
var object = new THREE.CSS3DSprite(canvas);
var object = new THREE.CSS3DSprite( image.cloneNode() );
object.position.x = Math.random() * 4000 - 2000,
object.position.y = Math.random() * 4000 - 2000,
object.position.z = Math.random() * 4000 - 2000
scene.add(object);
scene.add(object);
objects.push(object);
@@ -51,7 +45,7 @@
transition();
}, false);
sprite.src = 'textures/sprite.png';
image.src = 'textures/sprite.png';
// Plane
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,297 @@
/// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var material: THREE.SpriteMaterial;
var geometry: THREE.JSonLoaderResultGeometry;
var dat:any;
// -------
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = -250;
var container,stats;
var camera, scene;
var renderer;
var mesh, helper;
var mouseX = 0, mouseY = 0;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var clock = new THREE.Clock();
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
init();
animate();
function init() {
container = document.getElementById( 'container' );
camera = new THREE.PerspectiveCamera( 30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
camera.position.z = 2200;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 );
scene.add( camera );
// GROUND
var groundMaterial = new THREE.MeshPhongMaterial( { emissive: 0xbbbbbb } );
var planeGeometry = new THREE.PlaneGeometry( 16000, 16000 );
var ground = new THREE.Mesh( planeGeometry, groundMaterial );
ground.position.set( 0, FLOOR, 0 );
ground.rotation.x = -Math.PI/2;
scene.add( ground );
ground.receiveShadow = true;
// LIGHTS
var ambient = new THREE.AmbientLight( 0x222222 );
scene.add( ambient );
var light = new THREE.DirectionalLight( 0xebf3ff, 1.6 );
light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 );
scene.add( light );
light.castShadow = true;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
var d = 390;
light.shadowCameraLeft = -d * 2;
light.shadowCameraRight = d * 2;
light.shadowCameraTop = d * 1.5;
light.shadowCameraBottom = -d;
light.shadowCameraFar = 3500;
//light.shadowCameraVisible = true;
//
var light = new THREE.DirectionalLight( 0x497f13, 1 );
light.position.set( 0, -1, 0 );
scene.add( light );
// RENDERER
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
renderer.domElement.style.position = "relative";
renderer.setClearColor( scene.fog.color, 1 );
container.appendChild( renderer.domElement );
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.shadowMapEnabled = true;
// STATS
stats = new Stats();
container.appendChild( stats.domElement );
//
var loader = new THREE.JSONLoader();
loader.load( "models/skinned/knight.js", function ( geometry, materials ) {
createScene( geometry, materials, 0, FLOOR, -300, 60 )
} );
// GUI
initGUI();
//
window.addEventListener( 'resize', onWindowResize, false );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function ensureLoop( animation ) {
for ( var i = 0; i < animation.hierarchy.length; i ++ ) {
var bone = animation.hierarchy[ i ];
var first = bone.keys[ 0 ];
var last = bone.keys[ bone.keys.length - 1 ];
last.pos = first.pos;
last.rot = first.rot;
last.scl = first.scl;
}
}
function createScene( geometry, materials, x, y, z, s ) {
ensureLoop( geometry.animation );
geometry.computeBoundingBox();
var bb = geometry.boundingBox;
var path = "textures/cube/Park2/";
var format = '.jpg';
var urls = [
path + 'posx' + format, path + 'negx' + format,
path + 'posy' + format, path + 'negy' + format,
path + 'posz' + format, path + 'negz' + format
];
//var envMap = THREE.ImageUtils.loadTextureCube( urls );
//var map = THREE.ImageUtils.loadTexture( "textures/UV_Grid_Sm.jpg" );
//var bumpMap = THREE.ImageUtils.generateDataTexture( 1, 1, new THREE.Color() );
//var bumpMap = THREE.ImageUtils.loadTexture( "textures/water.jpg" );
for ( var i = 0; i < materials.length; i ++ ) {
var m = materials[ i ];
m.skinning = true;
m.morphTargets = true;
m.specular.setHSL( 0, 0, 0.1 );
m.color.setHSL( 0.6, 0, 0.6 );
m.ambient.copy( m.color );
//m.map = map;
//m.envMap = envMap;
//m.bumpMap = bumpMap;
//m.bumpScale = 2;
//m.combine = THREE.MixOperation;
//m.reflectivity = 0.75;
m.wrapAround = true;
}
mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) );
mesh.position.set( x, y - bb.min.y * s, z );
mesh.scale.set( s, s, s );
scene.add( mesh );
mesh.castShadow = true;
mesh.receiveShadow = true;
helper = new THREE.SkeletonHelper( mesh );
helper.material.linewidth = 3;
helper.visible = false;
scene.add( helper );
var animation = new THREE.Animation( mesh, geometry.animation );
animation.play();
}
function initGUI() {
var API = {
'show model' : true,
'show skeleton' : false
};
var gui = new dat.GUI();
gui.add( API, 'show model' ).onChange( function() { mesh.visible = API[ 'show model' ]; } );
gui.add( API, 'show skeleton' ).onChange( function() { helper.visible = API[ 'show skeleton' ]; } );
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
var delta = 0.75 * clock.getDelta();
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y = THREE.Math.clamp( camera.position.y + ( - mouseY - camera.position.y ) * .05, 0, 1000 );
camera.lookAt( scene.position );
// update skinning
THREE.AnimationHandler.update( delta );
if ( helper !== undefined ) helper.update();
// update morphs
if ( mesh ) {
var time = Date.now() * 0.001;
// mouth
mesh.morphTargetInfluences[ 1 ] = ( 1 + Math.sin( 4 * time ) ) / 2;
// frown ?
mesh.morphTargetInfluences[ 2 ] = ( 1 + Math.sin( 2 * time ) ) / 2;
// eyes
mesh.morphTargetInfluences[ 3 ] = ( 1 + Math.cos( 4 * time ) ) / 2;
}
renderer.render( scene, camera );
}
}
+9 -9
View File
@@ -49,11 +49,6 @@
var geometry = new THREE.BufferGeometry();
geometry.addAttribute('index', new Uint16Array(triangles * 3), 1);
geometry.addAttribute('position', new Float32Array(triangles * 3 * 3), 3);
geometry.addAttribute('normal', new Float32Array(triangles * 3 * 3), 3);
geometry.addAttribute('color', new Float32Array(triangles * 3 * 3), 3);
// break geometry into
// chunks of 21,845 triangles (3 unique vertices per triangle)
// for indices to fit into 16 bit integer number
@@ -61,7 +56,7 @@
var chunkSize = 21845;
var indices = geometry.getAttribute('index').array;
var indices = new Uint16Array( triangles * 3 );
for (var i = 0; i < indices.length; i++) {
@@ -69,9 +64,9 @@
}
var positions = geometry.getAttribute('position').array;
var normals = geometry.getAttribute('normal').array;
var colors = geometry.getAttribute('color').array;
var positions = new Float32Array( triangles * 3 * 3 );
var normals = new Float32Array( triangles * 3 * 3 );
var colors = new Float32Array( triangles * 3 * 3 );
var color = new THREE.Color();
@@ -167,6 +162,11 @@
}
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
var offsets = triangles / chunkSize;
for (var i = 0; i < offsets; i++) {
+1 -1
View File
@@ -85,7 +85,7 @@
}
var particles = new THREE.ParticleSystem(geometry, new THREE.ParticleSystemMaterial({ color: 0x888888 }));
var particles = new THREE.PointCloud( geometry, new THREE.PointCloudMaterial( { color: 0x888888 } ) );
scene.add(particles);
//
@@ -0,0 +1,335 @@
/// <reference path="../../three.d.ts" />
/// <reference path="../three-tests-setup.ts" />
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var material: THREE.SpriteMaterial;
var intersection: THREE.Intersection;
var container: HTMLElement;
var pcBuffer: THREE.PointCloud;
var v: any;
// -------
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
var renderer, scene, camera, stats;
var pointclouds;
var projector, raycaster, intersects;
var mouse = { x: 1, y: 1 };
var vector = new THREE.Vector3();
intersection = null;
var spheres = [];
var spheresIndex = 0;
var clock;
var threshold = 0.1;
var pointSize = 0.01;
var width = 150;
var length = 150;
var rotateY = new THREE.Matrix4().makeRotationY( 0.005 );
init();
animate();
function generatePointCloudGeometry( color, width, length ){
var geometry = new THREE.BufferGeometry();
var numPoints = width*length;
var positions = new Float32Array( numPoints*3 );
var colors = new Float32Array( numPoints*3 );
var k = 0;
for( var i = 0; i < width; i++ ) {
for( var j = 0; j < length; j++ ) {
var u = i / width;
var v = j / length;
var x = u - 0.5;
var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8 ) ) / 20;
var z = v - 0.5;
positions[ 3 * k ] = x;
positions[ 3 * k + 1 ] = y;
positions[ 3 * k + 2 ] = z;
var intensity = ( y + 0.1 ) * 5;
colors[ 3 * k ] = color.r * intensity;
colors[ 3 * k + 1 ] = color.g * intensity;
colors[ 3 * k + 2 ] = color.b * intensity;
k++;
}
}
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.computeBoundingBox();
return geometry;
}
function generatePointcloud( color, width, length ) {
var geometry = generatePointCloudGeometry( color, width, length );
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
return pointcloud;
}
function generateIndexedPointcloud( color, width, length ) {
var geometry = generatePointCloudGeometry( color, width, length );
var numPoints = width * length;
var indices = new Uint16Array( numPoints );
var k = 0;
for( var i = 0; i < width; i++ ) {
for( var j = 0; j < length; j++ ) {
indices[ k ] = k;
k++;
}
}
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
return pointcloud;
}
function generateIndexedWithOffsetPointcloud( color, width, length ){
var geometry = generatePointCloudGeometry( color, width, length );
var numPoints = width * length;
var indices = new Uint16Array( numPoints );
var k = 0;
for( var i = 0; i < width; i++ ){
for( var j = 0; j < length; j++ ) {
indices[ k ] = k;
k++;
}
}
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
var offset = { start: 0, count: indices.length, index: 0 };
geometry.offsets.push( offset );
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
return pointcloud;
}
function generateRegularPointcloud( color, width, length ) {
var geometry = new THREE.Geometry();
var numPoints = width * length;
var colors = [];
var k = 0;
for( var i = 0; i < width; i++ ) {
for( var j = 0; j < length; j++ ) {
var u = i / width;
v = j / length;
var x = u - 0.5;
var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8) ) / 20;
var z = v - 0.5;
v = new THREE.Vector3( x,y,z );
var intensity = ( y + 0.1 ) * 7;
colors[ 3 * k ] = color.r * intensity;
colors[ 3 * k + 1 ] = color.g * intensity;
colors[ 3 * k + 2 ] = color.b * intensity;
geometry.vertices.push( v );
colors[ k ] = ( color.clone().multiplyScalar( intensity ) );
k++;
}
}
geometry.colors = colors;
geometry.computeBoundingBox();
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
return pointcloud;
}
function init() {
container = document.getElementById( 'container' );
scene = new THREE.Scene();
clock = new THREE.Clock();
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.applyMatrix( new THREE.Matrix4().makeTranslation( 0,0,20 ) );
camera.applyMatrix( new THREE.Matrix4().makeRotationX( -0.5 ) );
//
pcBuffer = generatePointcloud( new THREE.Color( 1,0,0 ), width, length );
pcBuffer.scale.set( 10,10,10 );
pcBuffer.position.set( -5,0,5 );
scene.add( pcBuffer );
var pcIndexed = generateIndexedPointcloud( new THREE.Color( 0,1,0 ), width, length );
pcIndexed.scale.set( 10,10,10 );
pcIndexed.position.set( 5,0,5 );
scene.add( pcIndexed );
var pcIndexedOffset = generateIndexedWithOffsetPointcloud( new THREE.Color( 0,1,1 ), width, length );
pcIndexedOffset.scale.set( 10,10,10 );
pcIndexedOffset.position.set( 5,0,-5 );
scene.add( pcIndexedOffset );
var pcRegular = generateRegularPointcloud( new THREE.Color( 1,0,1 ), width, length );
pcRegular.scale.set( 10,10,10 );
pcRegular.position.set( -5,0,-5 );
scene.add( pcRegular );
pointclouds = [ pcBuffer, pcIndexed, pcIndexedOffset, pcRegular ];
//
var sphereGeometry = new THREE.SphereGeometry( 0.1, 32, 32 );
var sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, shading: THREE.FlatShading } );
for ( var i = 0; i < 40; i++ ) {
var sphere = new THREE.Mesh( sphereGeometry, sphereMaterial );
scene.add( sphere );
spheres.push( sphere );
}
//
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
//
projector = new THREE.Projector();
raycaster = new THREE.Raycaster();
raycaster.params.PointCloud.threshold = threshold;
//
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
//
window.addEventListener( 'resize', onWindowResize, false );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
}
function onDocumentMouseMove( event ) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
var toggle = 0;
function render() {
camera.applyMatrix( rotateY );
camera.updateMatrixWorld( true );
vector.set( mouse.x, mouse.y, 0.1 );
projector.unprojectVector( vector, camera );
raycaster.ray.set( camera.position, vector.sub( camera.position ).normalize() );
var intersections = raycaster.intersectObjects( pointclouds );
intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null;
if ( toggle > 0.02 && intersection !== null) {
spheres[ spheresIndex ].position.copy( intersection.point );
spheres[ spheresIndex ].scale.set( 1, 1, 1 );
spheresIndex = ( spheresIndex + 1 ) % spheres.length;
toggle = 0;
}
for ( var i = 0; i < spheres.length; i++ ) {
var sphere = spheres[ i ];
sphere.scale.multiplyScalar( 0.98 );
sphere.scale.clampScalar( 0.01, 1 );
}
toggle += clock.getDelta();
renderer.render( scene, camera );
}
}
+1 -1
View File
@@ -116,7 +116,7 @@
lensFlare.add(textureFlare3, 70, 1.0, THREE.AdditiveBlending);
lensFlare.customUpdateCallback = lensFlareUpdateCallback;
lensFlare.position = light.position;
lensFlare.position.copy( light.position );
scene.add(lensFlare);
+3 -7
View File
@@ -12,7 +12,7 @@
var container, stats;
var camera, scene, renderer, objects;
var particleLight, pointLight;
var particleLight;
var materials = [];
@@ -130,8 +130,8 @@
scene.add(directionalLight);
pointLight = new THREE.PointLight(0xffffff, 1);
scene.add(pointLight);
var pointLight = new THREE.PointLight(0xffffff, 1);
particleLight.add(pointLight);
//
@@ -228,10 +228,6 @@
particleLight.position.y = Math.cos(timer * 5) * 400;
particleLight.position.z = Math.cos(timer * 3) * 300;
pointLight.position.x = particleLight.position.x;
pointLight.position.y = particleLight.position.y;
pointLight.position.z = particleLight.position.z;
renderer.render(scene, camera);
}
@@ -42,10 +42,10 @@
}
material = new THREE.ParticleSystemMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true });
material = new THREE.PointCloudMaterial({ size: 35, sizeAttenuation: false, map: sprite, transparent: true });
material.color.setHSL(1.0, 0.3, 0.7);
particles = new THREE.ParticleSystem(geometry, material);
particles = new THREE.PointCloud(geometry, material);
particles.sortParticles = true;
scene.add(particles);
@@ -80,8 +80,6 @@
requestAnimationFrame(animate);
var time = Date.now();
object.rotation.x += 0.005;
object.rotation.y += 0.01;
+3
View File
@@ -26,12 +26,14 @@ THE SOFTWARE.
// webGL renderer test.
/// <reference path="./tests/webgl/webgl_animation_cloth.ts" />
/// <reference path="./tests/webgl/webgl_animation_skinning_morph.ts" />
/// <reference path="./tests/webgl/webgl_buffergeometry.ts" />
/// <reference path="./tests/webgl/webgl_camera.ts" />
/// <reference path="./tests/webgl/webgl_custom_attributes.ts" />
/// <reference path="./tests/webgl/webgl_geometries.ts" />
/// <reference path="./tests/webgl/webgl_helpers.ts" />
/// <reference path="./tests/webgl/webgl_interactive_cubes.ts" />
/// <reference path="./tests/webgl/webgl_interactive_raycasting_pointcloud.ts" />
/// <reference path="./tests/webgl/webgl_lensflares.ts" />
/// <reference path="./tests/webgl/webgl_lights_heimsphere.ts" />
/// <reference path="./tests/webgl/webgl_lines_colors.ts" />
@@ -54,3 +56,4 @@ THE SOFTWARE.
/// <reference path="./tests/canvas/canvas_lights_pointlights.ts" />
/// <reference path="./tests/canvas/canvas_materials.ts" />
/// <reference path="./tests/canvas/canvas_particles_floor.ts" />
+465 -245
View File
File diff suppressed because it is too large Load Diff