Merged with upstream

This commit is contained in:
gandjustas 2015-07-20 18:04:48 +03:00
commit 45a629eceb
2237 changed files with 1120172 additions and 868259 deletions

9
.editorconfig Normal file
View File

@ -0,0 +1,9 @@
root = true
[*]
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2

14
.gitignore vendored
View File

@ -23,18 +23,14 @@ Properties
*~
# test folder
!_infrastructure/*.js
!_infrastructure/tests/*
!_infrastructure/tests/*.js
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
_infrastructure/tests/build
.idea
*.iml
*.js.map
#rx.js
!rx.js
!*.js/
node_modules
.sublimets
.settings/launch.json

View File

@ -1,6 +1,8 @@
language: node_js
node_js:
- 0.10
- "0.10"
sudo: false
notifications:
email: false

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,180 @@
/// <reference path="DataStream.js.d.ts" />
var buf = new ArrayBuffer(100);
var ds = new DataStream(buf);
ds = new DataStream(buf, 10);
ds = new DataStream(buf, 10, DataStream.BIG_ENDIAN);
ds.save('somefile.ext');
ds.dynamicSize = true;
for (var i=0; i<ds.byteLength; i++) {
}
ds.buffer = buf;
ds.byteOffset = 10;
ds.seek(0);
ds.isEof();
var int32arr: Int32Array;
var int16arr: Int16Array;
var int8arr: Int8Array;
var uint32arr: Uint32Array;
var uint16arr: Uint16Array;
var uint8arr: Uint8Array;
var float64arr: Float64Array;
var float32arr: Float32Array;
var val: number;
var str: string;
int32arr = ds.mapInt32Array(2);
int32arr = ds.mapInt32Array(2, DataStream.LITTLE_ENDIAN);
int16arr = ds.mapInt16Array(2);
int16arr = ds.mapInt16Array(2, DataStream.BIG_ENDIAN);
int8arr = ds.mapInt8Array(2);
uint32arr = ds.mapUint32Array(2);
uint32arr = ds.mapUint32Array(2, DataStream.LITTLE_ENDIAN);
uint16arr = ds.mapUint16Array(2);
uint16arr = ds.mapUint16Array(2, DataStream.BIG_ENDIAN);
uint8arr = ds.mapUint8Array(2);
float64arr = ds.mapFloat64Array(2);
float64arr = ds.mapFloat64Array(2, DataStream.LITTLE_ENDIAN);
float32arr = ds.mapFloat32Array(2);
float32arr = ds.mapFloat32Array(2, DataStream.BIG_ENDIAN);
int32arr = ds.readInt32Array(2);
int32arr = ds.readInt32Array(2, DataStream.LITTLE_ENDIAN);
int16arr = ds.readInt16Array(2);
int16arr = ds.readInt16Array(2, DataStream.BIG_ENDIAN);
int8arr = ds.readInt8Array(2);
uint32arr = ds.readUint32Array(2);
uint32arr = ds.readUint32Array(2, DataStream.LITTLE_ENDIAN);
uint16arr = ds.readUint16Array(2);
uint16arr = ds.readUint16Array(2, DataStream.BIG_ENDIAN);
uint8arr = ds.readUint8Array(2);
float64arr = ds.readFloat64Array(2);
float64arr = ds.readFloat64Array(2, DataStream.LITTLE_ENDIAN);
float32arr = ds.readFloat32Array(2);
float32arr = ds.readFloat32Array(2, DataStream.BIG_ENDIAN);
ds.writeInt32Array(new Int32Array([1,2,3]));
ds.writeInt32Array(new Int32Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeInt16Array(new Int16Array([1,2,3]));
ds.writeInt16Array(new Int16Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeInt8Array(new Int8Array([1,2,3]));
ds.writeUint32Array(new Uint32Array([1,2,3]));
ds.writeUint32Array(new Uint32Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeUint16Array(new Uint16Array([1,2,3]));
ds.writeUint16Array(new Uint16Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeUint8Array(new Uint8Array([1,2,3]));
ds.writeFloat64Array(new Float64Array([1,2,3]));
ds.writeFloat64Array(new Float64Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeFloat32Array(new Float32Array([1,2,3]));
ds.writeFloat32Array(new Float32Array([1,2,3]), DataStream.BIG_ENDIAN);
val = ds.readInt32();
val = ds.readInt32(DataStream.LITTLE_ENDIAN);
val = ds.readInt16();
val = ds.readInt16(DataStream.BIG_ENDIAN);
val = ds.readInt8();
val = ds.readUint32();
val = ds.readUint32(DataStream.LITTLE_ENDIAN);
val = ds.readUint16();
val = ds.readUint16(DataStream.BIG_ENDIAN);
val = ds.readUint8();
val = ds.readFloat64();
val = ds.readFloat64(DataStream.LITTLE_ENDIAN);
val = ds.readFloat32();
val = ds.readFloat32(DataStream.BIG_ENDIAN);
ds.writeInt32(1);
ds.writeInt32(2, DataStream.BIG_ENDIAN);
ds.writeInt16(1);
ds.writeInt16(2, DataStream.LITTLE_ENDIAN);
ds.writeInt8(1);
ds.writeUint32(1);
ds.writeUint32(2, DataStream.BIG_ENDIAN);
ds.writeUint16(1);
ds.writeUint16(2, DataStream.LITTLE_ENDIAN);
ds.writeUint8(1);
ds.writeFloat32(1);
ds.writeFloat32(2, DataStream.BIG_ENDIAN);
ds.writeFloat64(1);
ds.writeFloat64(2, DataStream.LITTLE_ENDIAN);
var embed = [
'tag', 'uint32be',
'code', 'uint32le',
'greet', 'cstring'
];
var def = [
'tag', 'cstring:4',
'code', 'uint32le',
'embed', embed,
'length', 'uint16be',
'data', ['[]', 'float32be', 'length'],
'greet', 'cstring:20',
'endNote', 'uint8'
];
var obj = ds.readStruct(def);
ds.writeStruct(def, obj);
str = ds.readUCS2String(2);
str = ds.readUCS2String(2, DataStream.LITTLE_ENDIAN);
ds.writeUCS2String("str");
ds.writeUCS2String("str", DataStream.LITTLE_ENDIAN);
ds.writeUCS2String("str", DataStream.LITTLE_ENDIAN, 1);
str = ds.readString(2);
str = ds.readString(2, "ASCII");
ds.writeString("str");
ds.writeString("str", "ASCII");
ds.writeString("str", "ASCII", 1);
str = ds.readCString();
str = ds.readCString(2);
ds.writeCString("str");
ds.writeCString("str", 1);

937
DataStream.js/DataStream.js.d.ts vendored Normal file
View File

@ -0,0 +1,937 @@
// Type definitions for DataStream.js
// Project: https://github.com/kig/DataStream.js
// Definitions by: Tat <https://github.com/tatchx/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class DataStream {
/**
Big-endian const to use as default endianness.
*/
static BIG_ENDIAN: boolean;
/**
Little-endian const to use as default endianness.
*/
static LITTLE_ENDIAN: boolean;
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param {ArrayBuffer} arrayBuffer ArrayBuffer to read from.
*/
constructor(arrayBuffer: ArrayBuffer);
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param arrayBuffer ArrayBuffer to read from.
@param byteOffset Offset from arrayBuffer beginning for the DataStream.
*/
constructor(arrayBuffer: ArrayBuffer, byteOffset: number);
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param arrayBuffer ArrayBuffer to read from.
@param byteOffset Offset from arrayBuffer beginning for the DataStream.
@param endianness DataStream.BIG_ENDIAN or DataStream.LITTLE_ENDIAN (the default).
*/
constructor(arrayBuffer: ArrayBuffer, byteOffset: number, endianness: boolean);
/**
Saves the DataStream contents to the given filename.
Uses Chrome's anchor download property to initiate download.
*
@param filename Filename to save as.
@return nothing
*/
save(filename: string): void;
/**
Whether to extend DataStream buffer when trying to write beyond its size.
If set, the buffer is reallocated to twice its current size until the
requested write fits the buffer.
*/
dynamicSize: boolean;
/**
Returns the byte length of the DataStream object.
*/
byteLength: number;
/**
Set/get the backing ArrayBuffer of the DataStream object.
The setter updates the DataView to point to the new buffer.
*/
buffer: ArrayBuffer;
/**
Set/get the byteOffset of the DataStream object.
The setter updates the DataView to point to the new byteOffset.
*/
byteOffset: number;
/**
Set/get the backing DataView of the DataStream object.
The setter updates the buffer and byteOffset to point to the DataView values.
*/
dataView: Object;
/**
Sets the DataStream read/write position to given position.
Clamps between 0 and DataStream length.
*
@param pos Position to seek to.
@return nothing
*/
seek(pos: number): void;
/**
Returns true if the DataStream seek pointer is at the end of buffer and
there's no more data to read.
*
@return true if the seek pointer is at the end of the buffer.
*/
isEof(): boolean;
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Int32Array to the DataStream backing buffer.
*/
mapInt32Array(length: number): Int32Array;
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Int32Array to the DataStream backing buffer.
*/
mapInt32Array(length: number, e: boolean): Int32Array;
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Int16Array to the DataStream backing buffer.
*/
mapInt16Array(length: number): Int16Array;
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Int16Array to the DataStream backing buffer.
*/
mapInt16Array(length: number, e: boolean): Int16Array;
/**
Maps an Int8Array into the DataStream buffer.
*
Nice for quickly reading in data.
*
@param length Number of elements to map.
@return Int8Array to the DataStream backing buffer.
*/
mapInt8Array(length: number): Int8Array;
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Uint32Array to the DataStream backing buffer.
*/
mapUint32Array(length: number): Uint32Array;
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Uint32Array to the DataStream backing buffer.
*/
mapUint32Array(length: number, e: boolean): Uint32Array;
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Uint16Array to the DataStream backing buffer.
*/
mapUint16Array(length: number): Uint16Array;
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Uint16Array to the DataStream backing buffer.
*/
mapUint16Array(length: number, e: boolean): Uint16Array;
/**
Maps a Uint8Array into the DataStream buffer.
*
Nice for quickly reading in data.
*
@param length Number of elements to map.
@return Uint8Array to the DataStream backing buffer.
*/
mapUint8Array(length: number): Uint8Array;
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Float64Array to the DataStream backing buffer.
*/
mapFloat64Array(length: number): Float64Array;
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Float64Array to the DataStream backing buffer.
*/
mapFloat64Array(length: number, e: boolean): Float64Array;
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Float32Array to the DataStream backing buffer.
*/
mapFloat32Array(length: number): Float32Array;
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Float32Array to the DataStream backing buffer.
*/
mapFloat32Array(length: number, e: boolean): Float32Array;
/**
Reads an Int32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Int32Array.
*/
readInt32Array(length: number): Int32Array;
/**
Reads an Int32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Int32Array.
*/
readInt32Array(length: number, e: boolean): Int32Array;
/**
Reads an Int16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Int16Array.
*/
readInt16Array(length: number): Int16Array;
/**
Reads an Int16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Int16Array.
*/
readInt16Array(length: number, e: boolean): Int16Array;
/**
Reads an Int8Array of desired length from the DataStream.
*
@param length Number of elements to map.
@return The read Int8Array.
*/
readInt8Array(length: number): Int8Array;
/**
Reads an Uint32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Uint32Array.
*/
readUint32Array(length: number): Uint32Array;
/**
Reads an Uint32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Uint32Array.
*/
readUint32Array(length: number, e: boolean): Uint32Array;
/**
Reads an Uint16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Uint16Array.
*/
readUint16Array(length: number): Uint16Array;
/**
Reads an Uint16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Uint16Array.
*/
readUint16Array(length: number, e: boolean): Uint16Array;
/**
Reads an Uint8Array of desired length from the DataStream.
*
@param length Number of elements to map.
@return The read Uint8Array.
*/
readUint8Array(length: number): Uint8Array;
/**
Reads a Float64Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Float64Array.
*/
readFloat64Array(length: number, e: boolean): Float64Array;
/**
Reads a Float64Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Float64Array.
*/
readFloat64Array(length: number): Float64Array;
/**
Reads a Float32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Float32Array.
*/
readFloat32Array(length: number, e: boolean): Float32Array;
/**
Reads a Float32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Float32Array.
*/
readFloat32Array(length: number): Float32Array;
/**
Writes an Int32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeInt32Array(arr: Int32Array, e: boolean): void;
/**
Writes an Int32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeInt32Array(arr: Int32Array): void;
/**
Writes an Int16Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeInt16Array(arr: Int16Array, e: boolean): void;
/**
Writes an Int16Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeInt16Array(arr: Int16Array): void;
/**
Writes an Int8Array to the DataStream.
*
@param arr The array to write.
*/
writeInt8Array(arr: Int8Array): void;
/**
Writes an Uint32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeUint32Array(arr: Uint32Array, e: boolean): void;
/**
Writes an Uint32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeUint32Array(arr: Uint32Array): void;
/**
Writes an Uint16Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeUint16Array(arr: Uint16Array, e: boolean): void;
/**
Writes an Uint16Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeUint16Array(arr: Uint16Array): void;
/**
Writes an Uint8Array to the DataStream.
*
@param arr The array to write.
*/
writeUint8Array(arr: Uint8Array): void;
/**
Writes a Float64Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeFloat64Array(arr: Float64Array): void;
/**
Writes a Float64Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeFloat64Array(arr: Float64Array, e: boolean): void;
/**
Writes a Float32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeFloat32Array(arr: Float32Array): void;
/**
Writes a Float32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeFloat32Array(arr: Float32Array, e: boolean): void;
/**
Reads a 32-bit int from the DataStream with the desired endianness.
*
@return The read number.
*/
readInt32(): number;
/**
Reads a 32-bit int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readInt32(e: boolean): number;
/**
Reads a 16-bit int from the DataStream with the desired endianness.
*
@return The read number.
*/
readInt16(): number;
/**
Reads a 16-bit int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readInt16(e: boolean): number;
/**
Reads an 8-bit int from the DataStream.
*
@return The read number.
*/
readInt8(): number;
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
*
@return The read number.
*/
readUint32(): number;
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readUint32(e: boolean): number;
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
*
@return The read number.
*/
readUint16(): number;
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readUint16(e: boolean): number;
/**
Reads an 8-bit unsigned intfrom the DataStream.
*
@return The read number.
*/
readUint8(): number;
/**
Reads a 32-bit float from the DataStream with the desired endianness.
*
@return The read number.
*/
readFloat32(): number;
/**
Reads a 32-bit float from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readFloat32(e: boolean): number;
/**
Reads a 64-bit float from the DataStream with the desired endianness.
*
@return The read number.
*/
readFloat64(): number;
/**
Reads a 64-bit float from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readFloat64(e: boolean): number;
/**
Writes a 32-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeInt32(v: number): void;
/**
Writes a 32-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeInt32(v: number, e: boolean): void;
/**
Writes a 16-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeInt16(v: number): void;
/**
Writes a 16-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeInt16(v: number, e: boolean): void;
/**
Writes an 8-bit int to the DataStream.
*
@param v Number to write.
*/
writeInt8(v: number): void;
/**
Writes a 32-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeUint32(v: number): void;
/**
Writes a 32-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeUint32(v: number, e: boolean): void;
/**
Writes a 16-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeUint16(v: number): void;
/**
Writes a 16-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeUint16(v: number, e: boolean): void;
/**
Writes an 8-bit undigned int to the DataStream.
*
@param v Number to write.
*/
writeUint8(v: number): void;
/**
Writes a 32-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeFloat32(v: number): void;
/**
Writes a 32-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeFloat32(v: number, e: boolean): void;
/**
Writes a 64-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeFloat64(v: number): void;
/**
Writes a 64-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeFloat64(v: number, e: boolean): void;
/**
Reads a struct of data from the DataStream. The struct is defined as
a flat array of [name, type]-pairs. See the example below:
*
ds.readStruct([
'headerTag', 'uint32', // Uint32 in DataStream endianness.
'headerTag2', 'uint32be', // Big-endian Uint32.
'headerTag3', 'uint32le', // Little-endian Uint32.
'array', ['[]', 'uint32', 16], // Uint32Array of length 16.
'array2Length', 'uint32',
'array2', ['[]', 'uint32', 'array2Length'] // Uint32Array of length array2Length
]);
*
The possible values for the type are as follows:
*
// Number types
// Unsuffixed number types use DataStream endianness.
// To explicitly specify endianness, suffix the type with
// 'le' for little-endian or 'be' for big-endian,
// e.g. 'int32be' for big-endian int32.
'uint8' -- 8-bit unsigned int
'uint16' -- 16-bit unsigned int
'uint32' -- 32-bit unsigned int
'int8' -- 8-bit int
'int16' -- 16-bit int
'int32' -- 32-bit int
'float32' -- 32-bit float
'float64' -- 64-bit float
*
// String types
'cstring' -- ASCII string terminated by a zero byte.
'string:N' -- ASCII string of length N, where N is a literal integer.
'string:variableName' -- ASCII string of length $variableName,
where 'variableName' is a previously parsed number in the current struct.
'string,CHARSET:N' -- String of byteLength N encoded with given CHARSET.
'u16string:N' -- UCS-2 string of length N in DataStream endianness.
'u16stringle:N' -- UCS-2 string of length N in little-endian.
'u16stringbe:N' -- UCS-2 string of length N in big-endian.
*
// Complex types
[name, type, name_2, type_2, ..., name_N, type_N] -- Struct
function(dataStream, struct) {} -- Callback function to read and return data.
{get: function(dataStream, struct) {},
set: function(dataStream, struct) {}}
-- Getter/setter functions to read and return data, handy for using the same
struct definition for reading and writing structs.
['[]', type, length] -- Array of given type and length. The length can be either
a number, a string that references a previously-read
field, or a callback function(struct, dataStream, type){}.
If length is '*', reads in as many elements as it can.
*
@param structDefinition Struct definition object.
@return The read struct. Null if failed to read struct.
*/
readStruct(structDefinition: any[]): Object;
/**
Writes a struct to the DataStream. Takes a structDefinition that gives the
types and a struct object that gives the values. Refer to readStruct for the
structure of structDefinition.
*
@param structDefinition Type definition of the struct.
@param struct The struct data object.
*/
writeStruct(structDefinition: Object, struct: Object): void;
/**
Read UCS-2 string of desired length and endianness from the DataStream.
*
@param length The length of the string to read.
@return The read string.
*/
readUCS2String(length: number): string;
/**
Read UCS-2 string of desired length and endianness from the DataStream.
*
@param length The length of the string to read.
@param endianness The endianness of the string data in the DataStream.
@return The read string.
*/
readUCS2String(length: number, endianness: boolean): string;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
*/
writeUCS2String(str: string): void;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
@param endianness The endianness to use for the written string data.
*/
writeUCS2String(str: string, endianness: boolean): void;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
@param endianness The endianness to use for the written string data.
@param lengthOverride The number of characters to write.
*/
writeUCS2String(str: string, endianness: boolean, lengthOverride: number): void;
/**
Read a string of desired length and encoding from the DataStream.
*
@param length The length of the string to read in bytes.
@return The read string.
*/
readString(length: number): string;
/**
Read a string of desired length and encoding from the DataStream.
*
@param length The length of the string to read in bytes.
@param encoding The encoding of the string data in the DataStream. Defaults to ASCII.
@return The read string.
*/
readString(length: number, encoding: string): string;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
*/
writeString(s: string): void;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
@param encoding The encoding for the written string data. Defaults to ASCII.
*/
writeString(s: string, encoding: string): void;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
@param encoding The encoding for the written string data. Defaults to ASCII.
@param length The number of characters to write.
*/
writeString(s: string, encoding: string, length: number): void;
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
*
@return The read string.
*/
readCString(): string;
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
*
@param length The length of the string to read.
@return The read string.
*/
readCString(length: number): string;
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
*
@param s The string to write.
*/
writeCString(s: string): void;
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
*
@param s The string to write.
@param length The number of characters to write.
*/
writeCString(s: string, length: number): void;
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
*
@param t Type of the object to read.
@return Returns the object on successful read, null on unsuccessful.
*/
readType(t: Object): Object;
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
*
@param t Type of the object to read.
@param struct Struct to refer to when resolving length references and for calling callbacks.
@return Returns the object on successful read, null on unsuccessful.
*/
readType(t: Object, struct: Object): Object;
/**
Writes object v of type t to the DataStream.
*
@param t Type of data to write.
@param v Value of data to write.
@param struct Struct to pass to write callback functions.
*/
writeType(t: Object, v: Object, struct: Object): void;
}

View File

@ -0,0 +1,11 @@
/// <reference path="FileSaver.d.ts" />
/**
* @summary Test for "saveAs" function.
*/
function testSaveAs() {
var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
var filename: string = 'hello world.txt';
saveAs(data, filename);
}

27
FileSaver/FileSaver.d.ts vendored Normal file
View File

@ -0,0 +1,27 @@
// Type definitions for FileSaver.js
// Project: https://github.com/eligrey/FileSaver.js/
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* @summary Interface for "saveAs" function.
* @author Cyril Schumacher
* @version 1.0
*/
interface FileSaver {
(
/**
* @summary Data.
* @type {Blob}
*/
data: Blob,
/**
* @summary File name.
* @type {DOMString}
*/
filename: string
): void
}
declare var saveAs: FileSaver;

4
Finch/Finch.d.ts vendored
View File

@ -1,6 +1,6 @@
// Type definitions for Finch 0.5.13
// Project: https://github.com/stoodder/finchjs
// Definitions by: https://github.com/DavidSichau
// Project: https://github.com/stoodder/finchjs
// Definitions by: David Sichau <https://github.com/DavidSichau>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

View File

@ -0,0 +1,13 @@
/// <reference path="headroom.d.ts" />
new Headroom(document.getElementById('siteHead'));
new Headroom(document.getElementsByClassName('siteHead')[0]);
new Headroom(document.getElementsByClassName('siteHead')[0], {
tolerance: 34
});
new Headroom(document.getElementsByClassName('siteHead')[0], {
offset: 500
});

28
Headroom/headroom.d.ts vendored Normal file
View File

@ -0,0 +1,28 @@
// Type definitions for headroom.js v0.7.0
// Project: http://wicky.nillia.ms/headroom.js/
// Definitions by: Jakub Olek <https://github.com/hakubo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface HeadroomOptions {
offset?: number;
tolerance?: any;
classes?: {
initial?: string;
pinned?: string;
unpinned?: string;
top?: string;
notTop?: string;
};
scroller?: Element;
onPin?: () => void;
onUnPin?: () => void;
onTop?: () => void;
onNotTop?: () => void;
}
declare class Headroom {
constructor(element: Node, options?: HeadroomOptions);
constructor(element: Element, options?: HeadroomOptions);
init: () => void;
}

View File

@ -0,0 +1,15 @@
/// <reference path="JSONStream.d.ts" />
import json = require('JSONStream');
var read: NodeJS.ReadableStream;
var write: NodeJS.WritableStream;
read = read.pipe(json.parse('*'));
read = read.pipe(json.parse(['foo/*', 'bar/*']));
read = json.stringify();
read = json.stringify('{', ',', '}');
read = json.stringifyObject();
read = json.stringifyObject('{', ',', '}');

22
JSONStream/JSONStream.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
// Type definitions for JSONStream v0.8.0
// Project: http://github.com/dominictarr/JSONStream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'JSONStream' {
export interface Options {
recurse: boolean;
}
export function parse(pattern: any): NodeJS.ReadWriteStream;
export function parse(patterns: any[]): NodeJS.ReadWriteStream;
export function stringify(): NodeJS.ReadWriteStream;
export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
export function stringifyObject(): NodeJS.ReadWriteStream;
export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
}

View File

@ -1,5 +1,7 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
> The repository for *high quality* TypeScript type definitions.
For more information see the [definitelytyped.org](http://definitelytyped.org) website.
@ -30,7 +32,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi
## Requested definitions
Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest).
Here is are the [currently requested definitions](https://github.com/borisyankov/DefinitelyTyped/labels/Definition%3ARequest).
## Licence
@ -38,4 +40,4 @@ This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)

View File

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

View File

@ -1 +0,0 @@
tsc runner.ts --target ES5 --out runner.js --module commonjs --sourcemap

File diff suppressed because it is too large Load Diff

View File

@ -1,367 +0,0 @@
/// <reference path="typings/tsd.d.ts" />
/// <reference path="src/exec.ts" />
/// <reference path="src/file.ts" />
/// <reference path="src/tsc.ts" />
/// <reference path="src/timer.ts" />
/// <reference path="src/util.ts" />
/// <reference path="src/index.ts" />
/// <reference path="src/changes.ts" />
/// <reference path="src/printer.ts" />
/// <reference path="src/reporter/reporter.ts" />
/// <reference path="src/suite/suite.ts" />
/// <reference path="src/suite/syntax.ts" />
/// <reference path="src/suite/testEval.ts" />
/// <reference path="src/suite/tscParams.ts" />
module DT {
require('source-map-support').install();
// hacky typing
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var os = require('os');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var tsExp = /\.ts$/;
export var DEFAULT_TSC_VERSION = '0.9.7';
interface PackageJSON {
scripts: {[key:string]: string};
}
/////////////////////////////////
// Single test
/////////////////////////////////
export class Test {
constructor(public suite: ITestSuite, public tsfile: File, public options?: TscExecOptions) {
}
public run(): Promise<TestResult> {
return Tsc.run(this.tsfile.filePathWithName, this.options).then((execResult: ExecResult) => {
var testResult = new TestResult();
testResult.hostedBy = this.suite;
testResult.targetFile = this.tsfile;
testResult.options = this.options;
testResult.stdout = execResult.stdout;
testResult.stderr = execResult.stderr;
testResult.exitCode = execResult.exitCode;
return testResult;
});
}
}
/////////////////////////////////
// Parallel execute Tests
/////////////////////////////////
export class TestQueue {
private queue: Function[] = [];
private active: Test[] = [];
private concurrent: number;
constructor(concurrent: number) {
this.concurrent = Math.max(1, concurrent);
}
// add to queue and return a promise
run(test: Test): Promise<TestResult> {
var defer = Promise.defer();
// add a closure to queue
this.queue.push(() => {
// run it
var p = test.run();
p.then(defer.resolve.bind(defer), defer.reject.bind(defer));
p.finally(() => {
var i = this.active.indexOf(test);
if (i > -1) {
this.active.splice(i, 1);
}
this.step();
});
// return it
return test;
});
this.step();
// defer it
return defer.promise;
}
private step(): void {
while (this.queue.length > 0 && this.active.length < this.concurrent) {
this.active.push(this.queue.pop().call(null));
}
}
}
/////////////////////////////////
// Test results
/////////////////////////////////
export class TestResult {
hostedBy: ITestSuite;
targetFile: File;
options: TscExecOptions;
stdout: string;
stderr: string;
exitCode: number;
public get success(): boolean {
return this.exitCode === 0;
}
}
export interface ITestRunnerOptions {
tscVersion:string;
concurrent?:number;
testChanges?:boolean;
skipTests?:boolean;
printFiles?:boolean;
printRefMap?:boolean;
findNotRequiredTscparams?:boolean;
}
/////////////////////////////////
// The main class to kick things off
/////////////////////////////////
export class TestRunner {
private timer: Timer;
private suites: ITestSuite[] = [];
public changes: GitChanges;
public index: FileIndex;
public print: Print;
constructor(public dtPath: string, public options: ITestRunnerOptions = {tscVersion: DT.DEFAULT_TSC_VERSION}) {
this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams;
this.index = new FileIndex(this, this.options);
this.changes = new GitChanges(this);
this.print = new Print(this.options.tscVersion);
}
public addSuite(suite: ITestSuite): void {
this.suites.push(suite);
}
public checkAcceptFile(fileName: string): boolean {
var ok = tsExp.test(fileName);
ok = ok && fileName.indexOf('_infrastructure') < 0;
ok = ok && fileName.indexOf('node_modules/') < 0;
ok = ok && /^[a-z]/i.test(fileName);
return ok;
}
public run(): Promise<boolean> {
this.timer = new Timer();
this.timer.start();
this.print.printChangeHeader();
// only includes .d.ts or -tests.ts or -test.ts or .ts
return this.index.readIndex().then(() => {
return this.changes.readChanges();
}).then((changes: string[]) => {
this.print.printAllChanges(changes);
return this.index.collectDiff(changes);
}).then(() => {
this.print.printRemovals(this.index.removed);
this.print.printRelChanges(this.index.changed);
return this.index.parseFiles();
}).then(() => {
if (this.options.printRefMap) {
this.print.printRefMap(this.index, this.index.refMap);
}
if (Lazy(this.index.missing).some((arr: any[]) => arr.length > 0)) {
this.print.printMissing(this.index, this.index.missing);
this.print.printBoldDiv();
// bail
return Promise.cast(false);
}
if (this.options.printFiles) {
this.print.printFiles(this.index.files);
}
return this.index.collectTargets().then((files) => {
if (this.options.testChanges) {
this.print.printQueue(files);
return this.runTests(files);
}
else {
this.print.printTestAll();
return this.runTests(this.index.files)
}
}).then(() => {
return !this.suites.some((suite) => {
return suite.ngTests.length !== 0
});
});
});
}
private runTests(files: File[]): Promise<boolean> {
return Promise.attempt(() => {
assert(Array.isArray(files), 'files must be array');
var syntaxChecking = new SyntaxChecking(this.options);
var testEval = new TestEval(this.options);
if (!this.options.findNotRequiredTscparams) {
this.addSuite(syntaxChecking);
this.addSuite(testEval);
}
return Promise.all([
syntaxChecking.filterTargetFiles(files),
testEval.filterTargetFiles(files)
]);
}).spread((syntaxFiles, testFiles) => {
this.print.init(syntaxFiles.length, testFiles.length, files.length);
this.print.printHeader(this.options);
if (this.options.findNotRequiredTscparams) {
this.addSuite(new FindNotRequiredTscparams(this.options, this.print));
}
return Promise.reduce(this.suites, (count, suite: ITestSuite) => {
suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print);
this.print.printSuiteHeader(suite.testSuiteName);
if (this.options.skipTests) {
this.print.printWarnCode('skipped test');
return Promise.cast(count++);
}
return suite.start(files, (testResult) => {
this.print.printTestComplete(testResult);
}).then((suite) => {
this.print.printSuiteComplete(suite);
return count++;
});
}, 0);
}).then((count) => {
this.timer.end();
this.finaliseTests(files);
});
}
private finaliseTests(files: File[]): void {
var testEval: TestEval = Lazy(this.suites).filter((suite) => {
return suite instanceof TestEval;
}).first();
if (testEval) {
var existsTestTypings: string[] = Lazy(testEval.testResults).map((testResult) => {
return testResult.targetFile.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
var typings: string[] = Lazy(files).map((file) => {
return file.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
var withoutTestTypings: string[] = typings.filter((typing) => {
return existsTestTypings.indexOf(typing) < 0;
});
this.print.printDiv();
this.print.printTypingsWithoutTest(withoutTestTypings);
}
this.print.printDiv();
this.print.printTotalMessage();
this.print.printDiv();
this.print.printElapsedTime(this.timer.asString, this.timer.time);
this.suites.filter((suite: ITestSuite) => {
return suite.printErrorCount;
}).forEach((suite: ITestSuite) => {
this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length);
});
if (testEval) {
this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true);
}
this.print.printDiv();
if (this.suites.some((suite) => {
return suite.ngTests.length !== 0
})) {
this.print.printErrorsHeader();
this.suites.filter((suite) => {
return suite.ngTests.length !== 0;
}).forEach((suite) => {
suite.ngTests.forEach((testResult) => {
this.print.printErrorsForFile(testResult);
});
this.print.printBoldDiv();
});
}
}
}
var optimist: Optimist = require('optimist')(process.argv);
optimist.default('try-without-tscparams', false);
optimist.default('single-thread', false);
optimist.default('tsc-version', DEFAULT_TSC_VERSION);
optimist.default('test-changes', false);
optimist.default('skip-tests', false);
optimist.default('print-files', false);
optimist.default('print-refmap', false);
optimist.boolean('help');
optimist.describe('help', 'print help');
optimist.alias('h', 'help');
var argv: any = optimist.argv;
var dtPath = path.resolve(path.dirname((module).filename), '..', '..');
var cpuCores = os.cpus().length;
if (argv.help) {
optimist.showHelp();
var pkg: PackageJSON = require('../../package.json');
console.log('Scripts:');
console.log('');
Lazy(pkg.scripts).keys().each((key) => {
console.log(' $ npm run ' + key);
});
process.exit(0);
}
var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false;
new TestRunner(dtPath, {
concurrent: argv['single-thread'] ? 1 : Math.max(Math.min(24, cpuCores), 2),
tscVersion: argv['tsc-version'],
testChanges: testFull ? false : argv['test-changes'], // allow magic branch
skipTests: argv['skip-tests'],
printFiles: argv['print-files'],
printRefMap: argv['print-refmap'],
findNotRequiredTscparams: argv['try-without-tscparam']
}).run().then((success) => {
if (!success) {
process.exit(1);
}
}).catch((err) => {
throw err;
process.exit(2);
});
}

View File

@ -1,36 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
module DT {
'use strict';
var fs = require('fs');
var path = require('path');
var Git = require('git-wrapper');
var Promise: typeof Promise = require('bluebird');
export class GitChanges {
git;
options = {};
constructor(private runner: TestRunner) {
var dir = path.join(this.runner.dtPath, '.git');
if (!fs.existsSync(dir)) {
throw new Error('cannot locate git-dir: ' + dir);
}
this.options['git-dir'] = dir;
this.git = new Git(this.options);
this.git.exec = Promise.promisify(this.git.exec);
}
public readChanges(): Promise<string[]> {
var opts = {};
var args = ['--name-only HEAD~1'];
return this.git.exec('diff', opts, args).then((msg: string) => {
return msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g);
});
}
}
}

View File

@ -1,30 +0,0 @@
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var nodeExec = require('child_process').exec;
export class ExecResult {
error;
stdout = '';
stderr = '';
exitCode: number;
}
export function exec(filename: string, cmdLineArgs: string[]): Promise<ExecResult> {
return new Promise((resolve) => {
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, (error, stdout, stderr) => {
result.error = error;
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
resolve(result);
});
});
}
}

View File

@ -1,46 +0,0 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use strict';
var path = require('path');
export interface FileDict {
[fullPath:string]: File;
}
export interface FileArrDict {
[fullPath:string]: File[];
}
/////////////////////////////////
// Given a document root + ts file pattern this class returns:
// all the TS files OR just tests OR just definition files
/////////////////////////////////
export class File {
baseDir: string;
filePathWithName: string;
dir: string;
file: string;
ext: string;
fullPath: string;
references: File[] = [];
constructor(baseDir: string, filePathWithName: string) {
// why choose?
this.baseDir = baseDir;
this.filePathWithName = filePathWithName;
this.ext = path.extname(this.filePathWithName);
this.file = path.basename(this.filePathWithName, this.ext);
this.dir = path.dirname(this.filePathWithName);
this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext);
// lock it (shallow) (needs `use strict` in each file to work)
// Object.freeze(this);
}
toString(): string {
return '[File ' + this.filePathWithName + ']';
}
}
}

View File

@ -1,208 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
/// <reference path="util.ts" />
module DT {
'use strict';
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var readFile = Promise.promisify(fs.readFile);
/////////////////////////////////
// Track all files in the repo: map full path to File objects
/////////////////////////////////
export class FileIndex {
files: File[];
fileMap: FileDict;
refMap: FileArrDict;
options: ITestRunnerOptions;
changed: FileDict;
removed: FileDict;
missing: FileArrDict;
constructor(private runner: TestRunner, options: ITestRunnerOptions) {
this.options = options;
}
public hasFile(target: string): boolean {
return target in this.fileMap;
}
public getFile(target: string): File {
if (target in this.fileMap) {
return this.fileMap[target];
}
return null;
}
public setFile(file: File): void {
if (file.fullPath in this.fileMap) {
throw new Error('cannot overwrite file');
}
this.fileMap[file.fullPath] = file;
}
public readIndex(): Promise<void> {
this.fileMap = Object.create(null);
return Promise.promisify(glob).call(glob, '**/*.ts', {
cwd: this.runner.dtPath
}).then((filesNames: string[]) => {
this.files = Lazy(filesNames).filter((fileName) => {
return this.runner.checkAcceptFile(fileName);
}).map((fileName: string) => {
var file = new File(this.runner.dtPath, fileName);
this.fileMap[file.fullPath] = file;
return file;
}).toArray();
});
}
public collectDiff(changes: string[]): Promise<void> {
return new Promise((resolve) => {
// filter changes and bake map for easy lookup
this.changed = Object.create(null);
this.removed = Object.create(null);
Lazy(changes).filter((full) => {
return this.runner.checkAcceptFile(full);
}).uniq().each((local) => {
var full = path.resolve(this.runner.dtPath, local);
var file = this.getFile(full);
if (!file) {
// TODO figure out what to do here
// what does it mean? deleted?ss
file = new File(this.runner.dtPath, local);
this.setFile(file);
this.removed[full] = file;
// console.log('not in index? %', file.fullPath);
}
else {
this.changed[full] = file;
}
});
// console.log('changed:\n' + Object.keys(this.changed).join('\n'));
// console.log('removed:\n' + Object.keys(this.removed).join('\n'));
resolve();
});
}
public parseFiles(): Promise<void> {
return this.loadReferences(this.files).then(() => {
return this.getMissingReferences();
});
}
private getMissingReferences(): Promise<void> {
return Promise.attempt(() => {
this.missing = Object.create(null);
Lazy(this.removed).keys().each((removed) => {
if (removed in this.refMap) {
this.missing[removed] = this.refMap[removed];
}
});
});
}
private loadReferences(files: File[]): Promise<void> {
return new Promise((resolve, reject) => {
var queue = files.slice(0);
var active = [];
var max = 50;
var next = () => {
if (queue.length === 0 && active.length === 0) {
resolve();
return;
}
// queue paralel
while (queue.length > 0 && active.length < max) {
var file = queue.pop();
active.push(file);
this.parseFile(file).then((file) => {
active.splice(active.indexOf(file), 1);
next();
}).catch((err) => {
queue = [];
active = [];
reject(err);
});
}
};
next();
}).then(() => {
// bake reverse reference map (referenced to referrers)
this.refMap = Object.create(null);
Lazy(files).each((file) => {
Lazy(file.references).each((ref) => {
if (ref.fullPath in this.refMap) {
this.refMap[ref.fullPath].push(file);
}
else {
this.refMap[ref.fullPath] = [file];
}
});
});
});
}
// TODO replace with a stream?
private parseFile(file: File): Promise<File> {
return readFile(file.filePathWithName, {
encoding: 'utf8',
flag: 'r'
}).then((content) => {
file.references = Lazy(extractReferenceTags(content)).map((ref) => {
return path.resolve(path.dirname(file.fullPath), ref);
}).reduce((memo: File[], ref) => {
if (ref in this.fileMap) {
memo.push(this.fileMap[ref]);
}
else {
console.log('not mapped? -> ' + ref);
}
return memo;
}, []);
// return the object
return file;
});
}
public collectTargets(): Promise<File[]> {
return new Promise((resolve) => {
// map out files linked to changes
// - queue holds files touched by a change
// - pre-fill with actually changed files
// - loop queue, if current not seen:
// - add to result
// - from refMap queue all files referring to current
var result: FileDict = Object.create(null);
var queue = Lazy<File>(this.changed).values().toArray();
while (queue.length > 0) {
var next = queue.shift();
var fp = next.fullPath;
if (result[fp]) {
continue;
}
result[fp] = next;
if (fp in this.refMap) {
var arr = this.refMap[fp];
for (var i = 0, ii = arr.length; i < ii; i++) {
// just add it and skip expensive checks
queue.push(arr[i]);
}
}
}
resolve(Lazy<File>(result).values().toArray());
});
}
}
}

View File

@ -1,281 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
module DT {
var os = require('os');
/////////////////////////////////
// All the common things that we print are functions of this class
/////////////////////////////////
export class Print {
WIDTH = 77;
typings: number;
tests: number;
tsFiles: number
constructor(public version: string){
}
public init(typings: number, tests: number, tsFiles: number) {
this.typings = typings;
this.tests = tests;
this.tsFiles = tsFiles;
}
public out(s: any): Print {
process.stdout.write(s);
return this;
}
public repeat(s: string, times: number): string {
return new Array(times + 1).join(s);
}
public printChangeHeader() {
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n');
this.out('=============================================================================\n');
}
public printHeader(options: ITestRunnerOptions) {
var totalMem = Math.round(os.totalmem() / 1024 / 1024) + ' mb';
var freemem = Math.round(os.freemem() / 1024 / 1024) + ' mb';
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n');
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n');
this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n');
this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n');
this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n');
this.out(' \33[36m\33[1mTotal Memory :\33[0m ' + totalMem + '\n');
this.out(' \33[36m\33[1mFree Memory :\33[0m ' + freemem + '\n');
this.out(' \33[36m\33[1mCores :\33[0m ' + os.cpus().length + '\n');
this.out(' \33[36m\33[1mConcurrent :\33[0m ' + options.concurrent + '\n');
}
public printSuiteHeader(title: string) {
var left = Math.floor((this.WIDTH - title.length ) / 2) - 1;
var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1;
this.out(this.repeat('=', left)).out(' \33[34m\33[1m');
this.out(title);
this.out('\33[0m ').out(this.repeat('=', right)).printBreak();
}
public printDiv() {
this.out('-----------------------------------------------------------------------------\n');
}
public printBoldDiv() {
this.out('=============================================================================\n');
}
public printErrorsHeader() {
this.out('=============================================================================\n');
this.out(' \33[34m\33[1mErrors in files\33[0m \n');
this.out('=============================================================================\n');
}
public printErrorsForFile(testResult: TestResult) {
this.out('----------------- For file:' + testResult.targetFile.filePathWithName);
this.printBreak().out(testResult.stderr).printBreak();
}
public printBreak(): Print {
this.out('\n');
return this;
}
public clearCurrentLine(): Print {
this.out('\r\33[K');
return this;
}
public printSuccessCount(current: number, total: number) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printFailedCount(current: number, total: number) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printTypingsWithoutTestsMessage() {
this.out(' \33[36m\33[1mTyping without tests\33[0m\n');
}
public printTotalMessage() {
this.out(' \33[36m\33[1mTotal\33[0m\n');
}
public printElapsedTime(time: string, s: number) {
this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n');
}
public printSuiteErrorCount(errorHeadline: string, current: number, total: number, warn: boolean = false) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length));
if (warn) {
this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
else {
this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
}
public printSubHeader(file: string) {
this.out(' \33[36m\33[1m' + file + '\33[0m\n');
}
public printWarnCode(str: string) {
this.out(' \33[31m\33[1m<' + str.toLowerCase().replace(/ +/g, '-') + '>\33[0m\n');
}
public printLine(file: string) {
this.out(file + '\n');
}
public printElement(file: string) {
this.out(' - ' + file + '\n');
}
public printElement2(file: string) {
this.out(' - ' + file + '\n');
}
public printTypingsWithoutTestName(file: string) {
this.out(' - \33[33m\33[1m' + file + '\33[0m\n');
}
public printTypingsWithoutTest(withoutTestTypings: string[]) {
if (withoutTestTypings.length > 0) {
this.printTypingsWithoutTestsMessage();
this.printDiv();
withoutTestTypings.forEach((t) => {
this.printTypingsWithoutTestName(t);
});
}
}
public printTestComplete(testResult: TestResult): void {
var reporter = testResult.hostedBy.testReporter;
if (testResult.success) {
reporter.printPositiveCharacter(testResult);
}
else {
reporter.printNegativeCharacter(testResult);
}
}
public printSuiteComplete(suite: ITestSuite): void {
this.printBreak();
this.printDiv();
this.printElapsedTime(suite.timer.asString, suite.timer.time);
this.printSuccessCount(suite.okTests.length, suite.testResults.length);
this.printFailedCount(suite.ngTests.length, suite.testResults.length);
}
public printTests(adding: FileDict): void {
this.printDiv();
this.printSubHeader('Testing');
this.printDiv();
Object.keys(adding).sort().map((src) => {
this.printLine(adding[src].filePathWithName);
return adding[src];
});
}
public printQueue(files: File[]): void {
this.printDiv();
this.printSubHeader('Queued for testing');
this.printDiv();
files.forEach((file) => {
this.printLine(file.filePathWithName);
});
}
public printTestAll(): void {
this.printDiv();
this.printSubHeader('Ignoring changes, testing all files');
}
public printFiles(files: File[]): void {
this.printDiv();
this.printSubHeader('Files');
this.printDiv();
files.forEach((file) => {
this.printLine(file.filePathWithName);
file.references.forEach((file) => {
this.printElement(file.filePathWithName);
});
});
}
public printMissing(index: FileIndex, refMap: FileArrDict): void {
this.printDiv();
this.printSubHeader('Missing references');
this.printDiv();
Object.keys(refMap).sort().forEach((src) => {
var ref = index.getFile(src);
this.printLine('\33[31m\33[1m' + ref.filePathWithName + '\33[0m');
refMap[src].forEach((file) => {
this.printElement(file.filePathWithName);
});
});
}
public printAllChanges(paths: string[]): void {
this.printSubHeader('All changes');
this.printDiv();
paths.sort().forEach((line) => {
this.printLine(line);
});
}
public printRelChanges(changeMap: FileDict): void {
this.printDiv();
this.printSubHeader('Interesting files');
this.printDiv();
Object.keys(changeMap).sort().forEach((src) => {
this.printLine(changeMap[src].filePathWithName);
});
}
public printRemovals(changeMap: FileDict): void {
this.printDiv();
this.printSubHeader('Removed files');
this.printDiv();
Object.keys(changeMap).sort().forEach((src) => {
this.printLine(changeMap[src].filePathWithName);
});
}
public printRefMap(index: FileIndex, refMap: FileArrDict): void {
this.printDiv();
this.printSubHeader('Referring');
this.printDiv();
Object.keys(refMap).sort().forEach((src) => {
var ref = index.getFile(src);
this.printLine(ref.filePathWithName);
refMap[src].forEach((file) => {
this.printLine(' - ' + file.filePathWithName);
});
});
}
}
}

View File

@ -1,42 +0,0 @@
/// <reference path="../../_ref.d.ts" />
/// <reference path="../printer.ts" />
module DT {
/////////////////////////////////
// Test reporter interface
// for example, . and x
/////////////////////////////////
export interface ITestReporter {
printPositiveCharacter(testResult: TestResult):void;
printNegativeCharacter(testResult: TestResult):void;
}
/////////////////////////////////
// Default test reporter
/////////////////////////////////
export class DefaultTestReporter implements ITestReporter {
index = 0;
constructor(public print: Print) {
}
public printPositiveCharacter(testResult: TestResult) {
this.print.out('\33[36m\33[1m' + '.' + '\33[0m');
this.index++;
this.printBreakIfNeeded(this.index);
}
public printNegativeCharacter( testResult: TestResult) {
this.print.out('x');
this.index++;
this.printBreakIfNeeded(this.index);
}
private printBreakIfNeeded(index: number) {
if (index % this.print.WIDTH === 0) {
this.print.printBreak();
}
}
}
}

View File

@ -1,82 +0,0 @@
/// <reference path="../../runner.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// The interface for test suite
/////////////////////////////////
export interface ITestSuite {
testSuiteName:string;
errorHeadline:string;
filterTargetFiles(files: File[]): Promise<File[]>;
start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise<ITestSuite>;
testResults:TestResult[];
okTests:TestResult[];
ngTests:TestResult[];
timer:Timer;
testReporter:ITestReporter;
printErrorCount:boolean;
}
/////////////////////////////////
// Base class for test suite
/////////////////////////////////
export class TestSuiteBase implements ITestSuite {
timer: Timer = new Timer();
testResults: TestResult[] = [];
testReporter: ITestReporter;
printErrorCount = true;
queue: TestQueue;
constructor(public options: ITestRunnerOptions, public testSuiteName: string, public errorHeadline: string) {
this.queue = new TestQueue(options.concurrent);
}
public filterTargetFiles(files: File[]): Promise<File[]> {
throw new Error('please implement this method');
}
public start(targetFiles: File[], testCallback: (result: TestResult) => void): Promise<ITestSuite> {
this.timer.start();
return this.filterTargetFiles(targetFiles).then((targetFiles) => {
// tests get queued for multi-threading
return Promise.all(targetFiles.map((targetFile) => {
return this.runTest(targetFile).then((result) => {
testCallback(result);
});
}));
}).then(() => {
this.timer.end();
return this;
});
}
public runTest(targetFile: File): Promise<TestResult> {
return this.queue.run(new Test(this, targetFile, {
tscVersion: this.options.tscVersion
})).then((result) => {
this.testResults.push(result);
return result;
});
}
public get okTests(): TestResult[] {
return this.testResults.filter((r) => {
return r.success;
});
}
public get ngTests(): TestResult[] {
return this.testResults.filter((r) => {
return !r.success
});
}
}
}

View File

@ -1,26 +0,0 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var endDts = /\w\.d\.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
/////////////////////////////////
export class SyntaxChecking extends TestSuiteBase {
constructor(options: ITestRunnerOptions) {
super(options, 'Syntax checking', 'Syntax error');
}
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.cast(files.filter((file) => {
return endDts.test(file.filePathWithName);
}));
}
}
}

View File

@ -1,26 +0,0 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var endTestDts = /\w-tests?\.ts$/i;
/////////////////////////////////
// Compile with *-tests.ts
/////////////////////////////////
export class TestEval extends TestSuiteBase {
constructor(options) {
super(options, 'Typing tests', 'Failed tests');
}
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.cast(files.filter((file) => {
return endTestDts.test(file.filePathWithName);
}));
}
}
}

View File

@ -1,59 +0,0 @@
/// <reference path='../../runner.ts' />
/// <reference path='../file.ts' />
module DT {
'use strict';
var fs = require('fs');
var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// Try compile without .tscparams
// It may indicate that it is compatible with --noImplicitAny maybe...
/////////////////////////////////
export class FindNotRequiredTscparams extends TestSuiteBase {
testReporter: ITestReporter;
printErrorCount = false;
constructor(options: ITestRunnerOptions, private print: Print) {
super(options, 'Find not required .tscparams files', 'New arrival!');
this.testReporter = {
printPositiveCharacter: (testResult: TestResult) => {
this.print
.clearCurrentLine()
.printTypingsWithoutTestName(testResult.targetFile.filePathWithName);
},
printNegativeCharacter: (testResult: TestResult) => {
}
}
}
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.filter(files, (file) => {
return new Promise((resolve) => {
fs.exists(file.filePathWithName + '.tscparams', resolve);
});
});
}
public runTest(targetFile: File): Promise<TestResult> {
this.print.clearCurrentLine().out(targetFile.filePathWithName);
return this.queue.run(new Test(this, targetFile, {
tscVersion: this.options.tscVersion,
useTscParams: false,
checkNoImplicitAny: true
})).then((result) => {
this.testResults.push(result);
this.print.clearCurrentLine();
return result
});
}
public get ngTests(): TestResult[] {
// Do not show ng test results
return [];
}
}
}

View File

@ -1,50 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
module DT {
'use strict';
/////////////////////////////////
// Timer.start starts a timer
// Timer.end stops the timer and sets asString to the pretty print value
/////////////////////////////////
export class Timer {
startTime: number;
time = 0;
asString: string = '<not-started>'
public start() {
this.time = 0;
this.startTime = this.now();
this.asString = '<started>';
}
public now(): number {
return Date.now();
}
public end() {
this.time = (this.now() - this.startTime) / 1000;
this.asString = Timer.prettyDate(this.startTime, this.now());
}
public static prettyDate(date1: number, date2: number): string {
var diff = ((date2 - date1) / 1000);
var day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) {
return null;
}
return (<string><any> (day_diff == 0 && (
diff < 60 && (diff + ' seconds') ||
diff < 120 && '1 minute' ||
diff < 3600 && Math.floor(diff / 60) + ' minutes' ||
diff < 7200 && '1 hour' ||
diff < 86400 && Math.floor(diff / 3600) + ' hours') ||
day_diff == 1 && 'Yesterday' ||
day_diff < 7 && day_diff + ' days' ||
day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks'));
}
}
}

View File

@ -1,60 +0,0 @@
/// <reference path='../_ref.d.ts' />
/// <reference path='../runner.ts' />
/// <reference path='exec.ts' />
module DT {
'use strict';
var fs = require('fs');
var Promise: typeof Promise = require('bluebird');
export interface TscExecOptions {
tscVersion?: string;
useTscParams?: boolean;
checkNoImplicitAny?: boolean;
}
export class Tsc {
public static run(tsfile: string, options: TscExecOptions): Promise<ExecResult> {
var tscPath;
return new Promise.attempt(() => {
options = options || {};
options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION;
if (typeof options.checkNoImplicitAny === 'undefined') {
options.checkNoImplicitAny = true;
}
if (typeof options.useTscParams === 'undefined') {
options.useTscParams = true;
}
return fileExists(tsfile);
}).then((exists) => {
if (!exists) {
throw new Error(tsfile + ' does not exist');
}
tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
return fileExists(tscPath);
}).then((exists) => {
if (!exists) {
throw new Error(tscPath + ' does not exist');
}
return fileExists(tsfile + '.tscparams');
}).then(exists => {
if (exists) {
return readFile(tsfile + '.tscparams');
} else {
return new Promise('');
}
}).then((paramContents: string) => {
var command = 'node ' + tscPath + ' --module commonjs ';
if (options.useTscParams && paramContents.trim() !== '' && paramContents.trim() !== '""') {
command += '@' + tsfile + '.tscparams';
}
else if (options.checkNoImplicitAny) {
command += '--noImplicitAny';
}
return exec(command, [tsfile]);
});
}
}
}

View File

@ -1,52 +0,0 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use strict';
var fs = require('fs');
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var referenceTagExp = /<reference[ \t]*path=["']?([\w\.\/_-]*)["']?[ \t]*\/>/g;
export function endsWith(str: string, suffix: string) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
export function extractReferenceTags(source: string): string[] {
var ret: string[] = [];
var match: RegExpExecArray;
if (!referenceTagExp.global) {
throw new Error('referenceTagExp RegExp must have global flag');
}
referenceTagExp.lastIndex = 0;
while ((match = referenceTagExp.exec(source))) {
if (match.length > 0 && match[1].length > 0) {
ret.push(match[1]);
}
}
return ret;
}
export function fileExists(target: string): Promise<boolean> {
return new Promise((resolve, reject) => {
fs.exists(target, (bool: boolean) => {
resolve(bool);
});
});
}
export function readFile(target: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(target, 'utf-8', (err, contents: string) => {
if (err) {
reject(err);
} else {
resolve(contents);
}
});
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,252 +0,0 @@
// Type definitions for Lazy.js 0.3.2
// Project: https://github.com/dtao/lazy.js/
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module LazyJS {
interface LazyStatic {
<T>(value: T[]):ArrayLikeSequence<T>;
(value: any[]):ArrayLikeSequence<any>;
<T>(value: Object):ObjectLikeSequence<T>;
(value: Object):ObjectLikeSequence<any>;
(value: string):StringLikeSequence;
strict():LazyStatic;
generate<T>(generatorFn: GeneratorCallback<T>, length?: number):GeneratedSequence<T>;
range(to: number):GeneratedSequence<number>;
range(from: number, to: number, step?: number):GeneratedSequence<number>;
repeat<T>(value: T, count?: number):GeneratedSequence<T>;
on<T>(eventType: string):Sequence<T>;
readFile(path: string):StringLikeSequence;
makeHttpRequest(path: string):StringLikeSequence;
}
interface ArrayLike<T> {
length:number;
[index:number]:T;
}
interface Callback {
():void;
}
interface ErrorCallback {
(error: any):void;
}
interface ValueCallback<T> {
(value: T):void;
}
interface GetKeyCallback<T> {
(value: T):string;
}
interface TestCallback<T> {
(value: T):boolean;
}
interface MapCallback<T, U> {
(value: T):U;
}
interface MapStringCallback {
(value: string):string;
}
interface NumberCallback<T> {
(value: T):number;
}
interface MemoCallback<T, U> {
(memo: U, value: T):U;
}
interface GeneratorCallback<T> {
(index: number):T;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Iterator<T> {
new (sequence: Sequence<T>):Iterator<T>;
current():T;
moveNext():boolean;
}
interface GeneratedSequence<T> extends Sequence<T> {
new(generatorFn: GeneratorCallback<T>, length: number):GeneratedSequence<T>;
length():number;
}
interface AsyncSequence<T> extends SequenceBase<T> {
each(callback: ValueCallback<T>):AsyncHandle<T>;
}
interface AsyncHandle<T> {
cancel():void;
onComplete(callback: Callback):void;
onError(callback: ErrorCallback):void;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module Sequence {
function define(methodName: string[], overrides: Object): Function;
}
interface Sequence<T> extends SequenceBase<T> {
each(eachFn: ValueCallback<T>):Sequence<T>;
}
interface SequenceBase<T> extends SequenceBaser<T> {
first():any;
first(count: number):Sequence<T>;
indexOf(value: any, startIndex?: number):Sequence<T>;
last():any;
last(count: number):Sequence<T>;
lastIndexOf(value: any):Sequence<T>;
reverse():Sequence<T>;
}
interface SequenceBaser<T> {
// TODO improve define() (needs ugly overload)
async(interval: number):AsyncSequence<T>;
chunk(size: number):Sequence<T>;
compact():Sequence<T>;
concat(var_args: T[]):Sequence<T>;
consecutive(length: number):Sequence<T>;
contains(value: T):boolean;
countBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
countBy(propertyName: string): ObjectLikeSequence<T>;
dropWhile(predicateFn: TestCallback<T>): Sequence<T>;
every(predicateFn: TestCallback<T>): boolean;
filter(predicateFn: TestCallback<T>): Sequence<T>;
find(predicateFn: TestCallback<T>): Sequence<T>;
findWhere(properties: Object): Sequence<T>;
flatten(): Sequence<T>;
groupBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
initial(count?: number): Sequence<T>;
intersection(var_args: T[]): Sequence<T>;
invoke(methodName: string): Sequence<T>;
isEmpty(): boolean;
join(delimiter?: string): string;
map<U>(mapFn: MapCallback<T, U>): Sequence<U>;
max(valueFn?: NumberCallback<T>): T;
min(valueFn?: NumberCallback<T>): T;
pluck(propertyName: string): Sequence<T>;
reduce<U>(aggregatorFn: MemoCallback<T, U>, memo?: U): U;
reduceRight<U>(aggregatorFn: MemoCallback<T, U>, memo: U): U;
reject(predicateFn: TestCallback<T>): Sequence<T>;
rest(count?: number): Sequence<T>;
shuffle(): Sequence<T>;
some(predicateFn?: TestCallback<T>): boolean;
sortBy(sortFn: NumberCallback<T>): Sequence<T>;
sortedIndex(value: T): Sequence<T>;
sum(valueFn?: NumberCallback<T>): Sequence<T>;
takeWhile(predicateFn: TestCallback<T>): Sequence<T>;
union(var_args: T[]): Sequence<T>;
uniq(): Sequence<T>;
where(properties: Object): Sequence<T>;
without(var_args: T[]): Sequence<T>;
zip(var_args: T[]): Sequence<T>;
toArray(): T[];
toObject(): Object;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ArrayLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat(): ArrayLikeSequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
map<U>(mapFn: MapCallback<T, U>): ArrayLikeSequence<U>;
pop(): ArrayLikeSequence<T>;
rest(count?: number): ArrayLikeSequence<T>;
reverse(): ArrayLikeSequence<T>;
shift(): ArrayLikeSequence<T>;
slice(begin: number, end?: number): ArrayLikeSequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ObjectLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ObjectLikeSequence<T> extends Sequence<T> {
assign(other: Object): ObjectLikeSequence<T>;
// throws error
//async(): X;
defaults(defaults: Object): ObjectLikeSequence<T>;
functions(): Sequence<T>;
get(property: string): ObjectLikeSequence<T>;
invert(): ObjectLikeSequence<T>;
keys(): Sequence<string>;
omit(properties: string[]): ObjectLikeSequence<T>;
pairs(): Sequence<T>;
pick(properties: string[]): ObjectLikeSequence<T>;
toArray(): T[];
toObject(): Object;
values(): Sequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module StringLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface StringLikeSequence extends SequenceBaser<string> {
charAt(index: number): string;
charCodeAt(index: number): number;
contains(value: string): boolean;
endsWith(suffix: string): boolean;
first(): string;
first(count: number): StringLikeSequence;
indexOf(substring: string, startIndex?: number): number;
last(): string;
last(count: number): StringLikeSequence;
lastIndexOf(substring: string, startIndex?: number): number;
mapString(mapFn: MapStringCallback): StringLikeSequence;
match(pattern: RegExp): StringLikeSequence;
reverse(): StringLikeSequence;
split(delimiter: string): StringLikeSequence;
split(delimiter: RegExp): StringLikeSequence;
startsWith(prefix: string): boolean;
substring(start: number, stop?: number): StringLikeSequence;
toLowerCase(): StringLikeSequence;
toUpperCase(): StringLikeSequence;
}
}
declare var Lazy: LazyJS.LazyStatic;
declare module 'lazy.js' {
export = Lazy;
}

View File

@ -1,48 +0,0 @@
// https://github.com/substack/node-optimist
// sourced from https://github.com/soywiz/typescript-node-definitions/blob/master/optimist.d.ts
// rehacked by @Bartvds
declare module Optimist {
export interface Argv {
_: string[];
}
export interface Optimist {
default(name: string, value: any): Optimist;
default(args: any): Optimist;
boolean(name: string): Optimist;
boolean(names: string[]): Optimist;
string(name: string): Optimist;
string(names: string[]): Optimist;
wrap(columns): Optimist;
help(): Optimist;
showHelp(fn?: Function): Optimist;
usage(message: string): Optimist;
demand(key: string): Optimist;
demand(key: number): Optimist;
demand(key: string[]): Optimist;
alias(key: string, alias: string): Optimist;
describe(key: string, desc: string): Optimist;
options(key: string, opt: any): Optimist;
check(fn: Function);
parse(args: string[]): Optimist;
argv: Argv;
}
}
interface Optimist extends Optimist.Optimist {
(args: string[]): Optimist.Optimist;
}
declare module 'optimist' {
export = Optimist;
}

View File

@ -1,4 +0,0 @@
/// <reference path="node/node.d.ts" />
/// <reference path="bluebird/bluebird.d.ts" />
/// <reference path="lazy.js/lazy.js.d.ts" />
/// <reference path="optimist/optimist.d.ts" />

View File

@ -0,0 +1,36 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="acc-wizard.d.ts" />
/**
* @summary Test for "accwizard" without options.
*/
function testBasic() {
$('#test').accwizard();
}
/**
* @summary Test for "accwizard" with options.
*/
function testWithOptions() {
var options: AccWizardOptions = {
addButtons: true,
sidebar: '.acc-wizard-sidebar',
activeClass: 'acc-wizard-active',
completedClass: 'acc-wizard-completed',
todoClass: 'acc-wizard-todo',
stepClass: 'acc-wizard-step',
nextText: 'Next Step',
backText: 'Go Back',
nextType: 'submit',
backType: 'reset',
nextClasses: 'btn btn-primary',
backClasses: 'btn',
autoScrolling: true,
onNext: function() {},
onBack: function() {},
onInit: function() {},
onDestroy: function() {}
};
$('#test').accwizard(options);
}

101
acc-wizard/acc-wizard.d.ts vendored Normal file
View File

@ -0,0 +1,101 @@
// Type definitions for acc-wizard
// Project: https://github.com/sathomas/acc-wizard
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AccWizardOptions {
/**
* @summary Add next/prev buttons to panels.
* @type {boolean}
*/
addButtons: boolean;
/**
* @summary Selector for task sidebar.
* @type {string}
*/
sidebar: string;
/**
* @summary Class to indicate the active task in sidebar.
* @type {string}
*/
activeClass: string;
/**
* @summary Class to indicate task is complete.
* @type {string}
*/
completedClass: string;
/**
* @summary Class to indicate task is still pending.
* @type {string}
*/
todoClass: string;
/**
* @summary Class for step buttons within panels.
* @type {string}
*/
stepClass: string;
/**
* @summary Text for next button.
* @type {string}
*/
nextText: string;
/**
* @summary Text for back button
* @type {string}
*/
backType: string;
/**
* @summary Class(es) for next button.
* @type {string}
*/
nextClasses: string;
/**
* @summary Class(es) for back button.
* @type {string}
*/
backClasses: string;
/**
* @summary Auto-scrolling.
* @type {boolean}
*/
autoScrolling: boolean;
/**
* @summary Function to call on next step.
*/
onNext: Function;
/**
* @summary Function to call on back up.
*/
onBack: Function;
/**
* @summary A chance to hook initialization.
*/
onInit: Function;
/**
* @summary A chance to hook destruction.
*/
onDestroy: Function;
}
/**
* @summary Interface for "acc-wizard" JQuery plugin.
* @author Cyril Schumacher
* @version 1.0
*/
interface JQuery {
accwizard(options?: AccWizardOptions): void;
}

View File

@ -0,0 +1 @@
--noImplicitAny

47
ace/ace.d.ts vendored
View File

@ -576,7 +576,7 @@ declare module AceAjax {
/**
* Returns the current tab size.
**/
getTabSize(): string;
getTabSize(): number;
/**
* Returns `true` if the character at the position is a soft tab.
@ -1034,6 +1034,9 @@ declare module AceAjax {
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
**/
export interface Editor {
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any);
addEventListener(ev: string, callback: Function);
inMultiSelectMode: boolean;
@ -1060,6 +1063,31 @@ declare module AceAjax {
onChangeMode(e?);
execCommand(command:string, args?: any);
/**
* Sets a Configuration Option
**/
setOption(optionName: any, optionValue: any);
/**
* Sets Configuration Options
**/
setOptions(keyValueTuples: any);
/**
* Get a Configuration Option
**/
getOption(name: any):any;
/**
* Get Configuration Options
**/
getOptions():any;
/**
* Get rid of console warning by setting this to Infinity
**/
$blockScrolling:number;
/**
* Sets a new key handler, such as "vim" or "windows".
@ -1710,6 +1738,13 @@ declare module AceAjax {
**/
new(renderer: VirtualRenderer, session?: IEditSession): Editor;
}
interface EditorChangeEvent {
start: Position;
end: Position;
action: string; // insert, remove
lines: any[];
}
////////////////////////////////
/// PlaceHolder
@ -2574,6 +2609,16 @@ declare module AceAjax {
* Returns `true` if there are redo operations left to perform.
**/
hasRedo(): boolean;
/**
* Returns `true` if the dirty counter is 0
**/
isClean(): boolean;
/**
* Sets dirty counter to 0
**/
markClean(): void;
}
var UndoManager: {

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -0,0 +1,17 @@
/// <reference path='acl-mongodbBackend.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
import mongodb = require('mongodb');
var db: mongodb.Db;
// Using the mongo db backend
var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);

22
acl/acl-mongodbBackend.d.ts vendored Normal file
View File

@ -0,0 +1,22 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="acl.d.ts" />
/// <reference path="../mongodb/mongodb.d.ts" />
declare module "acl" {
import mongo = require('mongodb');
interface AclStatic {
mongodbBackend: MongodbBackendStatic;
}
interface MongodbBackend extends Backend<Callback> { }
interface MongodbBackendStatic {
new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend;
new(db: mongo.Db, prefix: string): MongodbBackend;
new(db: mongo.Db): MongodbBackend;
}
}

View File

@ -0,0 +1,16 @@
/// <reference path='acl-redisBackend.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
import redis = require('redis');
var client: redis.RedisClient;
// Using the redis backend
var acl = new Acl(new Acl.redisBackend(client, 'acl_'));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);

21
acl/acl-redisBackend.d.ts vendored Normal file
View File

@ -0,0 +1,21 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="acl.d.ts" />
/// <reference path='../redis/redis.d.ts'/>
declare module "acl" {
import redis = require('redis');
interface AclStatic {
redisBackend: RedisBackendStatic;
}
interface RedisBackend extends Backend<redis.RedisClient> { }
interface RedisBackendStatic {
new(redis: redis.RedisClient, prefix: string): RedisBackend;
new(redis: redis.RedisClient): RedisBackend;
}
}

65
acl/acl-tests.ts Normal file
View File

@ -0,0 +1,65 @@
/// <reference path='acl.d.ts'/>
// Sample code from
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
var report = <T>(err: Error, value: T) => {
if (err) {
console.error(err);
}
console.info(value);
};
// Using the memory backend
var acl = new Acl(new Acl.memoryBackend());
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
acl.addUserRoles('joed', 'guest');
acl.addRoleParents('baz', ['foo','bar']);
acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']);
acl.allow('admin', ['blogs','forums'], '*');
acl.allow([
{
roles:['guest','special-member'],
allows:[
{resources:'blogs', permissions:'get'},
{resources:['forums','news'], permissions:['get','put','delete']}
]
},
{
roles:['gold','silver'],
allows:[
{resources:'cash', permissions:['sell','exchange']},
{resources:['account','deposit'], permissions:['put','delete']}
]
}
]);
acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
if (res) {
console.log("User joed is allowed to view blogs");
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
acl.addUserRoles('jsmith', 'member');
}).then(() =>
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
).then((result) =>
console.dir('jsmith is allowed blogs ' + result)
).then(() => {
acl.allowedPermissions('james', ['blogs','forums'], report);
acl.allowedPermissions('jsmith', ['blogs','forums'], report);
});

120
acl/acl.d.ts vendored Normal file
View File

@ -0,0 +1,120 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path='../node/node.d.ts'/>
declare module "acl" {
import http = require('http');
import Promise = require("bluebird");
type strings = string|string[];
type Value = string|number;
type Values = Value|Value[];
type Action = () => any;
type Callback = (err: Error) => any;
type AnyCallback = (err: Error, obj: any) => any;
type AllowedCallback = (err: Error, allowed: boolean) => any;
type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value;
interface AclStatic {
new (backend: Backend<any>, logger: Logger, options: Option): Acl;
new (backend: Backend<any>, logger: Logger): Acl;
new (backend: Backend<any>): Acl;
memoryBackend: MemoryBackendStatic;
}
interface Logger {
debug: (msg: string)=>any;
}
interface Acl {
addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
userRoles: (userId: Value, cb?: (err: Error, roles: string[])=>any) => Promise<string[]>;
roleUsers: (role: Value, cb?: (err: Error, users: Values)=>any) => Promise<any>;
hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean)=>any) => Promise<boolean>;
addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>;
removeRole: (role: string, cb?: Callback) => Promise<void>;
removeResource: (resource: string, cb?: Callback) => Promise<void>;
allow: {
(roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>;
(aclSets: AclSet|AclSet[]): Promise<void>;
}
removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise<void>;
removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise<void>;
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise<any>;
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents: number, userId: Value|GetUserId, actions: strings) => Promise<any>;
}
interface Option {
buckets?: BucketsOption;
}
interface BucketsOption {
meta?: string;
parents?: string;
permissions?: string;
resources?: string;
roles?: string;
users?: string;
}
interface AclSet {
roles: strings;
allows: AclAllow[];
}
interface AclAllow {
resources: strings;
permissions: strings;
}
interface MemoryBackend extends Backend<Action[]> { }
interface MemoryBackendStatic {
new(): MemoryBackend;
}
//
// For internal use
//
interface Backend<T> {
begin: () => T;
end: (transaction: T, cb?: Action) => void;
clean: (cb?: Action) => void;
get: (bucket: string, key: Value, cb?: Action) => void;
union: (bucket: string, keys: Value[], cb?: Action) => void;
add: (transaction: T, bucket: string, key: Value, values: Values) => void;
del: (transaction: T, bucket: string, keys: Value[]) => void;
remove: (transaction: T, bucket: string, key: Value, values: Values) => void;
endAsync: Function; //TODO: Give more specific function signature
getAsync: Function;
cleanAsync: Function;
unionAsync: Function;
}
interface Contract {
(args: IArguments): Contract|NoOp;
debug: boolean;
fulfilled: boolean;
args: any[];
checkedParams: string[];
params: (...types: string[]) => Contract|NoOp;
end: () => void;
}
interface NoOp {
params: (...types: string[]) => NoOp;
end: () => void;
}
var _: AclStatic;
export = _;
}

30
acorn/acorn-tests.ts Normal file
View File

@ -0,0 +1,30 @@
/// <reference path="../estree/estree.d.ts" />
/// <reference path="acorn.d.ts" />
import acorn = require('acorn');
var token: acorn.Token;
var tokens: acorn.Token[];
var comment: acorn.Comment;
var comments: acorn.Comment[];
var program: ESTree.Program;
var any: any;
var string: string;
// acorn
string = acorn.version;
program = acorn.parse('code');
program = acorn.parse('code', {range: true, onToken: tokens, onComment: comments});
program = acorn.parse('code', {
ranges: true,
onToken: (token) => tokens.push(token),
onComment: (isBlock, text, start, end) => { }
});
// Token
token = tokens[0];
string = token.type.label;
any = token.value;
// Comment
string = comment.value;

67
acorn/acorn.d.ts vendored Normal file
View File

@ -0,0 +1,67 @@
// Type definitions for Acorn v1.0.1
// Project: https://github.com/marijnh/acorn
// Definitions by: RReverser <https://github.com/RReverser>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../estree/estree.d.ts" />
declare module acorn {
var version: string;
function parse(input: string, options?: Options): ESTree.Program;
function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression;
var defaultOptions: Options;
interface TokenType {
label: string;
keyword: string;
beforeExpr: boolean;
startsExpr: boolean;
isLoop: boolean;
isAssign: boolean;
prefix: boolean;
postfix: boolean;
binop: number;
updateContext: (prevType: TokenType) => any;
}
interface AbstractToken {
start: number;
end: number;
loc: ESTree.SourceLocation;
range: [number, number];
}
interface Token extends AbstractToken {
type: TokenType;
value: any;
}
interface Comment extends AbstractToken {
type: string;
value: string;
}
interface Options {
ecmaVersion?: number;
sourceType?: string;
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any;
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any;
allowReserved?: boolean;
allowReturnOutsideFunction?: boolean;
allowImportExportEverywhere?: boolean;
allowHashBang?: boolean;
locations?: boolean;
onToken?: ((token: Token) => any) | Token[];
onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[];
ranges?: boolean;
program?: ESTree.Program;
sourceFile?: string;
directSourceFile?: string;
preserveParens?: boolean;
plugins?: { [name: string]: Function; };
}
}
declare module "acorn" {
export = acorn
}

33
adm-zip/adm-zip-tests.ts Normal file
View File

@ -0,0 +1,33 @@
/// <reference path="adm-zip.d.ts" />
import AdmZip = require("adm-zip");
// reading archives
var zip = new AdmZip("./my_file.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function (zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.getData().toString('utf8'));
}
});
// outputs the content of some_folder/my_file.txt
console.log(zip.readAsText("some_folder/my_file.txt"));
// extracts the specified file to the specified location
zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true)
// extracts everything
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
// creating archives
var zip = new AdmZip();
// add file directly
zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here");
// add local file
zip.addLocalFile("/home/me/some_picture.png");
// get everything as a buffer
var willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/"/home/me/files.zip");

300
adm-zip/adm-zip.d.ts vendored Normal file
View File

@ -0,0 +1,300 @@
// Type definitions for adm-zip v0.4.4
// Project: https://github.com/cthackers/adm-zip
// Definitions by: John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module AdmZip {
class ZipFile {
/**
* Create a new, empty archive.
*/
constructor();
/**
* Read an existing archive.
*/
constructor(fileName: string);
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry String with the full path of the entry
* @return Buffer or Null in case of error
*/
readFile(entry: string): Buffer;
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry ZipEntry object
* @return Buffer or Null in case of error
*/
readFile(entry: IZipEntry): Buffer;
/**
* Asynchronous readFile
* @param entry String with the full path of the entry
* @param callback Called with a Buffer or Null in case of error
*/
readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void;
/**
* Asynchronous readFile
* @param entry ZipEntry object
* @param callback Called with a Buffer or Null in case of error
* @return Buffer or Null in case of error
*/
readFileAsync(entry: IZipEntry, callback: (data: Buffer, err: string) => any): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: string, encoding?: string): string;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry ZipEntry object
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: IZipEntry, encoding?: string): string;
/**
* Asynchronous readAsText
* @param entry String with the full path of the entry
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void;
/**
* Asynchronous readAsText
* @param entry ZipEntry object
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: IZipEntry, callback: (data: string) => any, encoding?: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry String with the full path of the entry
*/
deleteFile(entry: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry A ZipEntry object.
*/
deleteFile(entry: IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
* @param comment Content of the comment.
*/
addZipComment(comment: string): void;
/**
* Returns the zip comment
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry String with the full path of the entry
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string, comment: string): void;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry ZipEntry object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry String with the full path of the entry.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: string): string;
/**
* Returns the comment of the specified entry
* @param entry ZipEntry object.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry String with the full path of the entry.
* @param content The entry's new contents.
*/
updateFile(entry: string, content: Buffer): void;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry ZipEntry object.
* @param content The entry's new contents.
*/
updateFile(entry: IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
*/
addLocalFile(localPath: string, zipPath?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Defaults to an empty
* string.
*/
addLocalFolder(localPath: string, zipPath?: string): void;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null
* buffer should be provided.
* @param entryName Entry path
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
* @param attr Attribute to add to the entry.
*/
addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void;
/**
* Returns an array of ZipEntry objects representing the files and folders
* inside the archive
*/
getEntries(): IZipEntry[];
/**
* Returns a ZipEntry object representing the file or folder specified by
* ``name``.
* @param name Name of the file or folder to retrieve.
* @return ZipEntry The entry corresponding to the name.
*/
getEntry(name: string): IZipEntry;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*
* @return Boolean
*/
extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry ZipEntry object
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @return Boolean
*/
extractEntryTo(entryPath: IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no ``targetFileName`` is provided, it will
* overwrite the opened zip
* @param targetFileName
*/
writeZip(targetPath?: string): void;
/**
* Returns the content of the entire zip file as a Buffer object
* @return Buffer
*/
toBuffer(): Buffer;
}
/**
* The ZipEntry is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
}
declare module "adm-zip" {
import zipFile = AdmZip.ZipFile;
export = zipFile;
}

View File

@ -0,0 +1,32 @@
/// <reference path="alertify.d.ts" />
alertify.init();
alertify.alert("This is an alert");
alertify.alert("This is an alert with a callback", () => {
alertify.success("Alert finished");
}, "myCustomClass");
alertify.confirm("This is a confirm request");
alertify.confirm("This is a confirm request with a callback", () => {
alertify.success("Confirm finished");
}, "myCustomClass");
var custom = alertify.extend("custom");
alertify.log("log message 1");
alertify.log("log message 2", "success", 3000);
alertify.prompt("prompt message 1");
alertify.prompt("prompt message 2", () => { console.log("callback"); }, "ok", "myClass");
alertify.set({ delay: 1000 });
alertify.set({ labels: { ok: "OK", cancel: "Cancel" }});
alertify.set({ buttonFocus: "ok" });
alertify.set({ buttonReverse: true });
alertify.success("This is a success message");
alertify.error("This is an error message");
alertify.debug();

124
alertify/alertify.d.ts vendored Normal file
View File

@ -0,0 +1,124 @@
// Type definitions for alertify 0.3.11
// Project: http://fabien-d.github.io/alertify.js/
// Definitions by: John Jeffery <http://github.com/jjeffery>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var alertify: alertify.IAlertifyStatic;
declare module alertify {
interface IAlertifyStatic {
/**
* Create an alert dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
alert(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Create a confirm dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
confirm(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Extend the log method to create custom methods
* @param type Custom method name
* @return function for logging
* @since 0.0.1
*/
extend(type: string): (message: string, wait?: number) => IAlertifyStatic;
/**
* Initialize Alertify and create the 2 main elements.
* Initialization will happen automatically on the first
* use of alert, confirm, prompt or log.
* @since 0.0.1
*/
init(): void;
/**
* Show a new log message box
* @param message The message passed from the callee
* @param type Optional type of log message
* @param wait Optional time (in ms) to wait before auto-hiding
* @return alertify (ie this)
* @since 0.0.1
*/
log(message: string, type?: string, wait?: number): IAlertifyStatic;
/**
* Create a prompt dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param placeholder Default value for prompt input
* @param cssClass Class(es) to append to dialog
* @return alertify (ie this)
* @since 0.0.1
*/
prompt(message: string, fn?: Function, placeholder?: string, cssClass?: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
success(message: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
error(message: string): IAlertifyStatic;
/**
* Used to set alertify properties
* @param Properties
* @since 0.2.11
*/
set(args: IProperties): void;
/**
* The labels used for dialog buttons
*/
labels: ILabels;
/**
* Attaches alertify.error to window.onerror method
* @since 0.3.8
*/
debug(): void;
}
/**
* Properties for alertify.set function
*/
interface IProperties {
/** Default value for milliseconds display of log messages */
delay?: number;
/** Default values for display of labels */
labels?: ILabels;
/** Default button for focus */
buttonFocus?: string;
/** Should buttons be displayed in reverse order */
buttonReverse?: boolean;
}
/** Labels for altertify.set function */
interface ILabels {
ok?: string;
cancel?: string;
}
}

143
alt/alt-tests.ts Normal file
View File

@ -0,0 +1,143 @@
/**
* Created by shearerbeard on 6/28/15.
*/
///<reference path="alt.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
import Alt = require("alt");
import Promise = require("es6-promise");
//New alt instance
var alt = new Alt();
//Interfaces for our Action Types
interface TestActionsGenerate {
notifyTest(str:string):void;
}
interface TestActionsExplicit {
doTest(str:string):void;
success():void;
error():void;
loading():void;
}
//Create abstracts to inherit ghost methods
class AbstractActions implements AltJS.ActionsClass {
constructor( alt:AltJS.Alt){}
actions:any;
dispatch: ( ...payload:Array<any>) => void;
generateActions:( ...actions:Array<string>) => void;
}
class AbstractStoreModel<S> implements AltJS.StoreModel<S> {
bindActions:( ...actions:Array<Object>) => void;
bindAction:( ...args:Array<any>) => void;
bindListeners:(obj:any)=> void;
exportPublicMethods:(config:{[key:string]:(...args:Array<any>) => any}) => any;
exportAsync:( source:any) => void;
waitFor:any;
exportConfig:any;
getState:() => S;
}
class GenerateActionsClass extends AbstractActions {
constructor(config:AltJS.Alt) {
this.generateActions("notifyTest");
super(config);
}
}
class ExplicitActionsClass extends AbstractActions {
doTest(str:string) {
this.dispatch(str);
}
success() {
this.dispatch();
}
error() {
this.dispatch();
}
loading() {
this.dispatch();
}
}
var generatedActions = alt.createActions<TestActionsGenerate>(GenerateActionsClass);
var explicitActions = alt.createActions<ExplicitActionsClass>(ExplicitActionsClass);
interface AltTestState {
hello:string;
}
var testSource:AltJS.Source = {
fakeLoad():AltJS.SourceModel<string> {
return {
remote() {
return new Promise.Promise<string>((res:any, rej:any) => {
setTimeout(() => {
if(true) {
res("stuff");
} else {
rej("Things have broken");
}
}, 250)
});
},
local() {
return "local";
},
success: explicitActions.success,
error: explicitActions.error,
loading:explicitActions.loading
};
}
};
class TestStore extends AbstractStoreModel<AltTestState> implements AltTestState {
hello:string = "world";
constructor() {
super();
this.bindAction(generatedActions.notifyTest, this.onTest);
this.bindActions(explicitActions);
this.exportAsync(testSource);
this.exportPublicMethods({
split: this.split
});
}
onTest(str:string) {
this.hello = str;
}
onDoTest(str:string) {
this.hello = str;
}
split():string[] {
return this.hello.split("");
}
}
interface ExtendedTestStore extends AltJS.AltStore<AltTestState> {
fakeLoad():string;
split():Array<string>;
}
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(TestStore);
function testCallback(state:AltTestState) {
console.log(state);
}
//Listen allows a typed state callback
testStore.listen(testCallback);
testStore.unlisten(testCallback);
//State generic passes to derived store
var name:string = testStore.getState().hello;
var nameChars:Array<string> = testStore.split();
generatedActions.notifyTest("types");
explicitActions.doTest("more types");
export var result = testStore.getState();

167
alt/alt.d.ts vendored Normal file
View File

@ -0,0 +1,167 @@
// Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
declare module AltJS {
interface StoreReduce {
action:any;
data: any;
}
export interface StoreModel<S> {
//Actions
bindAction?( action:Action<any>, handler:ActionHandler):void;
bindActions?(actions:ActionsClass):void;
//Methods/Listeners
exportPublicMethods?(exportConfig:any):void;
bindListeners?(config:{[methodName:string]:Action<any> | Actions}):void;
exportAsync?(source:Source):void;
registerAsync?(datasource:Source):void;
//state
setState?(state:S):void;
setState?(stateFn:(currentState:S, nextState:S) => S):void;
getState?():S;
waitFor?(store:AltStore<any>):void;
//events
onSerialize?(fn:(data:any) => any):void;
onDeserialize?(fn:(data:any) => any):void;
on?(event:AltJS.lifeCycleEvents, callback:() => any):void;
emitChange?():void;
waitFor?(storeOrStores:AltStore<any> | Array<AltStore<any>>):void;
otherwise?(data:any, action:AltJS.Action<any>):void;
observe?(alt:Alt):any;
reduce?(state:any, config:StoreReduce):Object;
preventDefault?():void;
afterEach?(payload:Object, state:Object):void;
beforeEach?(payload:Object, state:Object):void;
// TODO: Embed dispatcher interface in def
dispatcher?:any;
//instance
getInstance?():AltJS.AltStore<S>;
alt?:Alt;
displayName?:string;
}
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any):any;
remote(state:any):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}
export interface AltStore<S> {
getState():S;
listen(handler:(state:S) => any):() => void;
unlisten(handler:(state:S) => any):void;
emitChange():void;
}
export enum lifeCycleEvents {
bootstrap,
snapshot,
init,
rollback,
error
}
export type Actions = {[action:string]:Action<any>};
export interface Action<T> {
( args:T):void;
defer(data:any):void;
}
export interface ActionsClass {
generateActions?( ...action:Array<string>):void;
dispatch( ...payload:Array<any>):void;
actions?:Actions;
}
type StateTransform = (store:StoreModel<any>) => AltJS.AltStore<any>;
interface AltConfig {
dispatcher?:any;
serialize?:(serializeFn:(data:Object) => string) => void;
deserialize?:(deserializeFn:(serialData:string) => Object) => void;
storeTransforms?:Array<StateTransform>;
batchingFunction?:(callback:( ...data:Array<any>) => any) => void;
}
class Alt {
constructor(config?:AltConfig);
actions:Actions;
bootstrap(jsonData:string):void;
takeSnapshot( ...storeNames:Array<string>):string;
flush():Object;
recycle( ...stores:Array<AltJS.AltStore<any>>):void;
rollback():void;
dispatch(action?:AltJS.Action<any>, data?:Object, details?:any):void;
//Actions methods
addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object):T;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array<any>):T;
generateActions<T>( ...actions:Array<string>):T;
getActions(actionsName:string):AltJS.Actions;
//Stores methods
addStore(name:string, store:StoreModel<any>, saveStore?:boolean):void;
createStore<S>(store:StoreModel<S>, name?:string):AltJS.AltStore<S>;
getStore(name:string):AltJS.AltStore<any>;
}
export interface AltFactory {
new(config?:AltConfig):Alt;
}
type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass;
type ActionHandler = ( ...data:Array<any>) => any;
type ExportConfig = {[key:string]:(...args:Array<any>) => any};
}
declare module "alt/utils/chromeDebug" {
function chromeDebug(alt:AltJS.Alt):void;
export = chromeDebug;
}
declare module "alt/AltContainer" {
import React = require("react");
interface ContainerProps {
store?:AltJS.AltStore<any>;
stores?:Array<AltJS.AltStore<any>>;
inject?:{[key:string]:any};
actions?:{[key:string]:Object};
render?:(...props:Array<any>) => React.ReactElement<any>;
flux?:AltJS.Alt;
transform?:(store:AltJS.AltStore<any>, actions:any) => any;
shouldComponentUpdate?:(props:any) => boolean;
component?:React.Component<any, any>;
}
type AltContainer = React.ReactElement<ContainerProps>;
var AltContainer:React.ComponentClass<ContainerProps>;
export = AltContainer;
}
declare module "alt" {
var alt:AltJS.AltFactory;
export = alt;
}

View File

@ -1 +1 @@
""

View File

@ -1 +1 @@
""

View File

@ -1,10 +1,10 @@
/// <reference path="../jquery/jquery.d.ts" />
// Type definitions for AmplifyJs 1.1.0
// Project: http://amplifyjs.com/
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface amplifyRequestSettings {
resourceId: string;
data?: any;
@ -50,7 +50,7 @@ interface amplifyRequest {
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings);
(settings: amplifyRequestSettings): any;
/***
* Define a resource.

View File

@ -1 +1 @@
""

View File

@ -0,0 +1,80 @@
/// <reference path="./amqp-rpc.d.ts" />
import amqp_rpc = require('amqp-rpc');
var rpc = amqp_rpc.factory();
interface Name {
name?: string;
}
rpc.on<number>('inc', function (param, cb) {
var prevVal = param;
var nextVal = param + 2;
cb(++param, prevVal, nextVal);
});
rpc.on<Name>('say.*', function (param, cb, inf) {
var arr = inf.cmd.split('.');
var name = (param && param.name) ? param.name : 'world';
cb(arr[1] + ' ' + name + '!');
});
rpc.on('withoutCB', function (param, cb, inf) {
if (cb) {
cb('please run function without cb parameter')
}
else {
console.log('this is function withoutCB');
}
});
rpc.call<number>('inc', 5, function (param1, param2, param3) {
console.log(param1, param2, param3);
});
rpc.call<Name>('say.Hello', { name: 'John' }, function (msg) {
console.log('results of say.Hello:', msg); //output: Hello John!
});
rpc.call<any>('withoutCB', {}, function (msg) {
console.log('withoutCB results:', msg); //output: please run function without cb parameter
});
rpc.call<any>('withoutCB', {}); //output message on server side console
import os = require('os');
interface State {
type: string;
}
var counter = 0;
rpc.onBroadcast<State>('getWorkerStat', function (params, cb) {
if (params && params.type == 'fullStat') {
cb(null, {
pid: process.pid,
hostname: os.hostname(),
uptime: process.uptime(),
counter: counter++
});
}
else {
cb(null, { counter: counter++ })
}
});
var all_stats: any = {};
rpc.callBroadcast<State>(
'getWorkerStat',
{ type: 'fullStat' }, //request parameters
{ //call options
ttl: 1000, //wait response time (1 seconds), after run onComplete
onResponse: function (err: any, stat: any) { //callback on each worker response
all_stats[stat.hostname + ':' + stat.pid] = stat;
},
onComplete: function () { //callback on ttl expired
console.log('----------------------- WORKER STATISTICS ----------------------------------------');
for (var worker in all_stats) {
var s: any = all_stats[worker];
console.log(worker, '\tuptime=', s.uptime.toFixed(2) + ' seconds', '\tcounter=', s.counter);
}
}
});

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